简体   繁体   English

iOS UIImageView剪辑/蒙版图片

[英]iOS UIImageView clip/mask image

Basically, I am making a view that has two images. 基本上,我正在制作一个有两个图像的视图。 Image one is shown in a right triangle that takes up the top left of the view, and image two takes the up the right triangle that takes up the bottom right. 图像1以直角三角形显示,占据视图的左上角,图像2显示右侧三角形,占据右下角。

Imagine a square cut diagonally, a different image exists in each resulting half. 想象一下对角线方形切割,每个产生的一半都存在不同的图像。

I've been reading a lot about masks, but I don't want to use another image to mask these images. 我一直在阅读很多关于面具的内容,但我不想使用其他图像来掩盖这些图像。

I'm looking for a way to give it 3 points, which form that triangle, and then have it clip the image that way. 我正在寻找一种方法来给它3点,形成三角形,然后让它剪切图像。

I feel like this is probably easy to do in Coregraphics, I'm just missing the calls I think. 我觉得这在Coregraphics中可能很容易做到,我只是错过了我认为的电话。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

Here's one way, using clipping paths on an image context. 这是一种方法,在图像上下文中使用剪切路径。 The example is for an image size of 256 x 256, but you should easily be able to adapt it to your needs. 示例是图像大小为256 x 256,但您应该能够轻松地根据您的需要进行调整。

UIGraphicsBeginImageContext(CGSizeMake(256, 256));
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, 256); 
CGContextConcatCTM(context, flipVertical);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 0, 256);
CGContextAddLineToPoint(context, 256, 256);
CGContextClosePath(context);
CGContextSaveGState(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, 256, 256), [image1 CGImage]);
CGContextRestoreGState(context);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 256, 0);
CGContextAddLineToPoint(context, 256, 256);
CGContextClosePath(context);
CGContextSaveGState(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, 256, 256), [image2 CGImage]);
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); // image contains the result
UIGraphicsEndImageContext();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM