0

我有一个包含 UIImageView 的 UIView,我对 UIImageView 应用了旋转变换,然后想在 CGContext 中使用相同的旋转变换绘制该图像(将来将使用更多的变换,如平移和缩放),我有以下代码在 CGContext 中进行转换和绘图:

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);

.

问题是输出图像看起来与 UIKit 的 UIVIew 中显示的不一样,它会倾斜并且位置也不准确,这是一个屏幕截图:

在此处输入图像描述

请指导我做错了什么,感谢您的帮助:)

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

更新 我已经尝试过[imageView.image drawAtPoint:modifiedRect.origin];纠正偏斜问题(http://screencast.com/t/v2oKkmkd),但位置问题仍然存在:(

更新 2 这是一个带有少许修改代码的测试项目:https ://github.com/abduliam/TestTransform

4

1 回答 1

1

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

例如,这将绘制旋转 -15 度的图像:

    CGRect clipped = CGRectInset(screenRect, 100, 100);
    CGContextRotateCTM(ctx,  -15 * M_PI / 180.0);
    [imageView.image drawInRect: clipped];
于 2014-12-31T13:39:53.993 回答