Saving 2 UIImages to one while saving rotation, resize info and its quality

后端 未结 2 1856
刺人心
刺人心 2021-01-19 05:05

I want to save 2 UIImages that are moved, resized and rotated by user. The problem is i dont want to use such function as any \'printscreen one\', because it makes both imag

2条回答
  •  青春惊慌失措
    2021-01-19 05:45

    You have to set the transform of the context to match your imageView's transform before you start drawing into it.

    i.e.,

    CGAffineTransform transform = CGAffineTransformIdentity;
    transform = CGAffineTransformTranslate(transform, boundingRect.size.width/2, boundingRect.size.height/2);
    transform = CGAffineTransformRotate(transform, angle);
    transform = CGAffineTransformScale(transform, 1.0, -1.0);
    
    CGContextConcatCTM(context, transform);
    
    // Draw the image into the context
    CGContextDrawImage(context, CGRectMake(-imageView.image.size.width/2, -imageView.image.size.height/2, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
    
    // Get an image from the context
    rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
    

    and check out Creating a UIImage from a rotated UIImageView.

    EDIT: if you don't know the angle of rotation of the image you can get the transform from the layer property of the UIImageView:

    UIGraphicsBeginImageContext(rotatedImageView.image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform transform = rotatedImageView.transform;
    transform = CGAffineTransformScale(transform, 1.0, -1.0);
    CGContextConcatCTM(context, transform);
    
    // Draw the image into the context
    CGContextDrawImage(context, CGRectMake(0, 0, rotatedImageView.image.size.width, rotatedImageView.image.size.height), rotatedImageView.image.CGImage);
    
    // Get an image from the context
    UIImage *newRotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
    
    UIGraphicsEndImageContext();
    

    You will have to play about with the transform matrix to centre the image in the context and you will also have to calculate a bounding rectangle for the rotated image or it will be cropped at the corners (i.e., rotatedImageView.image.size is not big enough to encompass a rotated version of itself).

提交回复
热议问题