为什么 CGContextDrawImage 旋转我的图像

Why is CGContextDrawImage rotating my image

我正在尝试用 CGContext 更改 UIImage 区域的颜色,然后从当前状态创建一个新图像。原始图像的方向正确,但在此之后,图像转向一边。

CGRect imageRect = CGRectMake(0, 0, originalImage.size.width, originalImage.size.height);

 UIGraphicsBeginImageContextWithOptions(originalImage.size, false, originalImage.scale);
 CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);
CGContextDrawImage(context, imageRect, originalImage.CGImage);
CGContextSetRGBFillColor(context, 255.0f, 255.0f, 255.0f, 1.0f);
CGContextFillRect(context, CGRectMake(5,5,100,100));
CGContextRotateCTM (context, radians(270));
CGContextRestoreGState(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

这是一个非常简单的问题。

因为iOS系统有3个不同的坐标系。

UIKit - y轴方向向下 Core Graphics(Quartz) - y轴方向向上 OpenGL ES - y轴方向向上

原图是UIKit创建的,目标图是Core Graphics创建的,应该是倒过来的。

如果你想得到正确的图像,你可以使用:

UIImageView* imageV = [[UIImageView alloc] initWithFrame:CGRectMake(100,100, 100, 100)];
imageV.layer.borderColor = [UIColor redColor].CGColor;
imageV.layer.borderWidth = 1;
imageV.image = img;
imageV.layer.transform = CATransform3DRotate(imageV.layer.transform, M_PI, 1.0f, 0.0f, 0.0f);
[self.view addSubview:imageV];

希望对您有所帮助。