2013-07-26 20 views
0

我有一个包含UIImageView的UIView,我将旋转变换应用到UIImageView,然后想要在CGContext中使用相同的旋转变换绘制该图像(以及将来更多的变换,如转换和规模将被使用),我有以下代码进行CGContext中的转换和绘制:用CGContext绘制CGAffineTransform的UIImage奇怪的输出

UIImage *image=[UIImage imageNamed:@"cena-1.png"]; 
CGRect imageFrame=CGRectMake(50, 50, image.size.width, image.size.height); 
UIImageView *imageView=[[UIImageView alloc] initWithFrame:imageFrame]; 
imageView.image=image; 
[self.view addSubview:imageView]; 

CGAffineTransform imageTransform=CGAffineTransformMakeRotation(degreesToRadians(10)); 
imageView.transform=imageTransform; 
NSLog(@"self.imgOverlay.image.scale: %f", imageView.image.scale); 

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale); 
CGContextRef context = UIGraphicsGetCurrentContext(); 
UIGraphicsPushContext(context); 

CGContextConcatCTM(context, imageView.transform); 

CGRect modifiedRect=CGRectApplyAffineTransform(imageFrame, imageTransform); 
[imageView.image drawInRect:modifiedRect]; 

UIGraphicsPopContext(); 
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

NSString *jpgPath=[NSTemporaryDirectory() stringByAppendingPathComponent:@"test.jpg"]; 
NSData *imageData=UIImageJPEGRepresentation(outputImage, 1.0); 
[imageData writeToFile:jpgPath atomically:YES]; 

NSLog(@"putputImage path: %@", jpgPath); 

问题是outputimage看起来不一样,因为它是UIKit中的UIView的显示,它被扭曲和位置是不准确的为好,这里是截图:

enter image description here

请指引我关于我在做什么错,谢谢你的帮助:)

ps我还发布了另一个问题(https://stackoverflow.com/questions/17873202/uiimage-drawn-in-cgcontext-with-cgaffinetransform-unexpected-results),解释了完整的场景,但对这个问题的回答有望足够。

UPDATE 我试图[imageView.image drawAtPoint:modifiedRect.origin];它纠正歪斜问题(http://screencast.com/t/v2oKkmkd),但位置问题仍然:(

更新2 下面是一个测试项目,一点点修改后的代码:https://github.com/abduliam/TestTransform

+1

尝试使用PNG表示...有时JPEG功能莫名其妙地不工作,但PNG功能一样。 –

+0

@DylanKirkby感谢您的评论,尝试过(http://screencast.com/t/0mgge4LEHRF)没有运气,情况更加复杂,我认为它与CG和UIKit的坐标系的差异有关: ) –

回答

1

不是旋转矩形,而是旋转整个图形上下文,然后在该矩形中绘制它。

对于示例嘞,这将绘制图像旋转15度:

CGRect clipped = CGRectInset(screenRect, 100, 100); 
    CGContextRotateCTM(ctx, -15 * M_PI/180.0); 
    [imageView.image drawInRect: clipped]; 
+0

感谢您花时间回答我的问题:)我确实设法解决了这个问题,不记得是什么解决方案,但是它可以在appstore上的行动中看到:https://itunes.apple.com/GB /应用/以上的价格-ME-大头/ id645765826 –