Mask arbitrarily sized UIImageView with resizable UIImage mask

calayer, ios, uiimage, uiimageview

Solution

I was wrong. That answer can be modified to work for asymmetrical images. I worked on that answer a bit and solved my own problem.

The following code made my cap insets work for the mask layer:

mask.contentsCenter =
CGRectMake(BubbleRightCapInsets.left/rightBubbleBackground.size.width,
BubbleRightCapInsets.top/rightBubbleBackground.size.height,
1.0/rightBubbleBackground.size.width,
1.0/rightBubbleBackground.size.height);

Result:

Problem

Current code: ``` self.backgroundImageView.image = [self.message imageOfSize:self.message.size]; // Random image, random size UIImage *rightBubbleBackground = [[UIImage imageNamed:@"BubbleRight"] resizableImageWithCapInsets:BubbleRightCapInsets resizingMode:UIImageResizingModeStretch]; CALayer *mask = [CALayer layer]; mask.contents = (id)[rightBubbleBackground CGImage]; mask.frame = self.backgroundImageView.layer.frame; self.backgroundImageView.layer.mask = mask; self.backgroundImageView.layer.masksToBounds = YES; ``` This does not work properly. Though the mask is applied, the `rightBubbleBackground` does not resize correctly to fit `self.backgroundImageView`, even though it has resizing cap insets (`BubbleRightCapInsets`) set. Original Image: Mask image (`rightBubbleBackground`): Result: I found this answer but it only works for symmetrical images. Maybe I could modify that answer for my use.

Original source

Related problems