Mask arbitrarily sized UIImageView with resizable UIImage mask

Viewed 2155

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:

Original image

Mask image (rightBubbleBackground):

Mask

Result:

Result

I found this answer but it only works for symmetrical images. Maybe I could modify that answer for my use.

2 Answers
Related