How to get a rotated, zoomed and panned image from an UIImageView at its full resolution?

前端 未结 3 1934
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 23:28

I have an UIImageView which can be rotated, panned and scaled with gesture recognisers. As a result it is cropped in its enclosing view. Everything is worki

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 00:07

    Why capturing the view if you have the original image? Just apply the transformations to it. Something like this may be a start:

    UIImage *image = [UIImage imageNamed:@"<# original #>"];
    
    CIImage *cimage = [CIImage imageWithCGImage:image.CGImage];
    
    // build the transform you want
    CGAffineTransform t = CGAffineTransformIdentity;
    CGFloat angle = [(NSNumber *)[self.faceImageView valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
    CGFloat scale = [(NSNumber *)[self.faceImageView valueForKeyPath:@"layer.transform.scale"] floatValue];    
    t = CGAffineTransformConcat(t, CGAffineTransformMakeScale(scale, scale));
    t = CGAffineTransformConcat(t, CGAffineTransformMakeRotation(-angle));
    
    // create a new CIImage using the transform, crop, filters, etc.
    CIImage *timage = [cimage imageByApplyingTransform:t];
    
    // draw the result
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef imageRef = [context createCGImage:timage fromRect:[timage extent]];
    UIImage *result = [UIImage imageWithCGImage:imageRef];
    
    // save to disk
    NSData *png = UIImagePNGRepresentation(result);
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/result.png"];
    if (png && [png writeToFile:path atomically:NO]) {
        NSLog(@"\n%@", path);
    }
    CGImageRelease(imageRef);
    

    You can easily crop the output if that's what you want (see -[CIImage imageByCroppingToRect] or take into account the translation, apply a Core Image filter, etc. depending on what are your exact needs.

提交回复
热议问题