Create UIImage cutout

Deadly 提交于 2019-12-09 13:58:21

问题


I have a UIView containing 2 UIImageViews - a frame and a picture behind the frame. The frame is not a rectangle - it's an irregular shape. The user can manipulate the picture behind the frame (zoom, rotate and pan) and when they're done, I want to capture the cutout of the picture within the frame - not the picture and the frame together. Is there a way I can do this?

I've managed to flatten the picture and the frame together in to a single image as below, but I only want the picture, which if extracted successfully will have a border in the shape of the frame.

- (IBAction)renderPhoto:(id)sender {
    //Combine the layers into a single image
    UIView *canvas = [[[sender superview] subviews] objectAtIndex:0];
    UIGraphicsBeginImageContext(canvas.bounds.size);
    [canvas.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *combinedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

回答1:


You could create a mask from your frame and apply this mask to the target image to essentially cut the frame off the target image. Or, depending how you end up using the final image, it may be simpler to clip the context using the frame while you perform your drawing.

This topic covers it all: https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-TPXREF101

The second option (clipping the context) is under Masking an Image by Clipping the Context.




回答2:


use my this method..

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{

    UIGraphicsBeginImageContext(photo.frame.size);/// use your screen or photo frame
    [photo.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();



    CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];

    /*    no origin .....
    UIGraphicsBeginImageContext(tempview.frame.size);
    [[self.photo layer] renderInContext:UIGraphicsGetCurrentContext()];   
    cropped= UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext(); 
    */
        return cropped;
}

Hope,this help you.... :)



来源:https://stackoverflow.com/questions/10517589/create-uiimage-cutout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!