UIImage orientation is changing when drawing in UI

2019-09-10 04:19发布

I want to draw some lines on the UIImage. I am able to draw the lines in to the Context and at the end I am drawing the background image to it before getting image from the context with the below code:

UIGraphicsBeginImageContext(self.bounds.size);
CGRect newFrame = self.frame;
newFrame.origin.y = 0;
[self.backgroundImage drawInRect:newFrame];

[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

problem is: self.backgroundImage.imageOrientation is 3 but saveImage.imageOrientation is 0. how can I get the same imageOrientation for the saveImage?

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-10 04:43

UIImage->drawInRect will honor the image orientation, so after that call, the result is always "upright", therefore your saveImage should actually have imageOrientationUp.

If you want to change the orientation metadata without affecting the image, you can use something like the following:

// Recreate UIImage with new orientation

- (UIImage *) imageWithOrientation:(UIImageOrientation)value
{
    if (self.imageOrientation == value)
        return self;

    if (self.CGImage != nil)
        return [UIImage imageWithCGImage:self.CGImage
        scale:self.scale orientation:value];

    if (self.CIImage != nil)
        return [UIImage imageWithCIImage:self.CIImage
        scale:self.scale orientation:value];

    return nil;
}
查看更多
登录 后发表回答