Triangular UIView or UIImageView

Akshit Zaveri picture Akshit Zaveri · Feb 14, 2014 · Viewed 11.3k times · Source

I have requirement like below image.

enter image description here

But, i'm confused about how to achieve this? Can i achieved it by using 3 UIImageViews or UIViews. If both then, which one is better? Finally, i have to combine three images & make one from that three images. I should be able to get touch of image too. I have no idea about this. Thanks.

Answer

Cyrille picture Cyrille · Feb 14, 2014

Every UIView has a backing CALayer (accessible by aview.layer).

Every CALayer has a mask property, which is another CALayer. A mask allows to define a see-through shape for the layer, like a stencil.

So you need three UIImageViews, each of them has a different .layer.mask, each of these masks is a different CAShapeLayer whose .path are triangular CGPaths.

// Build a triangular path
UIBezierPath *path = [UIBezierPath new];
[path moveToPoint:(CGPoint){0, 0}];
[path addLineToPoint:(CGPoint){40, 40}];
[path addLineToPoint:(CGPoint){100, 0}];
[path addLineToPoint:(CGPoint){0, 0}];

// Create a CAShapeLayer with this triangular path
// Same size as the original imageView
CAShapeLayer *mask = [CAShapeLayer new];
mask.frame = imageView.bounds;
mask.path = path.CGPath;

// Mask the imageView's layer with this shape
imageView.layer.mask = mask;

Repeat three times.