Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask arbitrarily sized UIImageView with resizable UIImage mask

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.

like image 306
duci9y Avatar asked Dec 08 '13 12:12

duci9y


1 Answers

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:

Result

like image 90
duci9y Avatar answered Nov 15 '22 01:11

duci9y