创buildUIImage剪影

我有一个UIView包含2个UIImageViews – 框架和框架后面的图片。 框架不是一个矩形 – 它是一个不规则的形状。 用户可以操纵画框后面的图片(缩放,旋转和平移),当他们完成时,我想要捕捉画框内的图片剪切 – 而不是图片和框架在一起。 有什么办法可以做到这一点?

我已经设法将图片和框架拼合成一个单一的图像如下,但我只想要的图片,如果成功提取将具有边框的形状。

 - (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(); } 

您可以从您的框架中创build一个遮罩,并将此遮罩应用于目标图像,从而将帧从目标图像上切除。 或者,取决于如何使用最终图像,在执行绘图时使用框架剪辑上下文可能会更简单。

本主题涵盖了这一切: https : //developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-TPXREF101

第二个选项(裁剪上下文)是在通过裁剪上下文掩盖图像下 。

用我的这个方法..

 - (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; } 

希望,这可以帮助你…. 🙂