Forum Xamarin.iOS

Unable to get UIImageView mask image to work

I have a UIImageView which is intended to hold a picture in a chat view. I would like to mask the image with a chat bubble background, so the effect is one of simply a chat bubble filled with the image. The picture is resized if it overflows certain boundary conditions, and all sizing is handled via autolayout with constraints.

I can't get the chat bubble image mask to work. Relevant sample:

pictureView = new UIImageView() { ContentMode = UIViewContentMode.ScaleAspectFit, ClipsToBounds = true }; pictureView.Image = new UIImage("venue_placeholder"); UIImage bubble = new UIImage("bub_in_blk"); UIImage stretchableBubble = bubble.CreateResizableImage(new UIEdgeInsets(13f, 20f, 13f, 14f), UIImageResizingMode.Stretch); CALayer maskLayer = new CALayer(); maskLayer.Contents = stretchableBubble.CGImage; maskLayer.ContentsScale = bubble.CurrentScale; maskLayer.ContentsCenter = new CGRect(20f / stretchableBubble.Size.Width, 13f / stretchableBubble.Size.Height, 22f / stretchableBubble.Size.Width, 19f / stretchableBubble.Size.Height); pictureView.Layer.Mask = maskLayer; pictureView.Layer.MasksToBounds = true;
And then down in my constraint update area I'm doing some logic and then setting a calculated Width and Height for the pictureView component:
pictureView.UpdateConstraints(make => { make.Height.EqualTo(new NSNumber(desiredHeight)); make.Width.EqualTo(new NSNumber(desiredWidth)); });
And the "bub_in_blk" image is a small chat bubble with a transparent background and a solid black chat bubble.

When I run, I get simply a blank area on the screen, sized appropriately for my specified width and height.

My resizing code looks to be good, as when I simply set the pictureView Layer (instead of Layer.Mask) to be my stretched image, it displays a correct chat bubble:
pictureView.Image = new UIImage("venue_placeholder"); UIImage bubble = new UIImage("bub_in_blk"); UIImage stretchableBubble = bubble.CreateResizableImage(new UIEdgeInsets(13f, 20f, 13f, 14f), UIImageResizingMode.Stretch); CALayer maskLayer = pictureView.Layer; maskLayer.Contents = stretchableBubble.CGImage; maskLayer.ContentsScale = bubble.CurrentScale; maskLayer.ContentsCenter = new CGRect(20f / stretchableBubble.Size.Width, 13f / stretchableBubble.Size.Height, 22f / stretchableBubble.Size.Width, 19f / stretchableBubble.Size.Height);
Yields:

Where am I going wrong with Layer.Mask?

Tagged:
Sign In or Register to comment.