Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask a UIView

I'm working on an app where I draw a UIView via code and I fill it with a UIColor. Next thing I want to load a mask.png file (no transparency, just black and white) and mask the UIView to change its visual appearance.

Any idea how to do this?

like image 636
Thomas Joos Avatar asked Jun 17 '10 07:06

Thomas Joos


People also ask

What is masking in Swift?

SwiftUI gives us the mask() modifier for masking one with another, which means you can mask an image using text or an image using an image, or more. For example, this creates a 300x300 image of stripes, then masks it using the text “SWIFT!” so that the letters act as a cut out for the image: Image("laser-show") .

What is mask to bounds?

A Boolean indicating whether sublayers are clipped to the layer's bounds.

What is Calayer in Swift?

An object that manages image-based content and allows you to perform animations on that content.


2 Answers

// Create your mask layer CALayer* maskLayer = [CALayer layer]; maskLayer.frame = CGRectMake(0,0,yourMaskWidth ,yourMaskHeight); maskLayer.contents = (__bridge id)[[UIImage imageNamed:@"yourMaskImage.png"] CGImage];  // Apply the mask to your uiview layer         yourUIView.layer.mask = maskLayer; 

Remember to import QuartzCore and add the framework

#import <QuartzCore/QuartzCore.h> 

It is very easy but I didn't find the answer anywhere!

like image 86
JEzu Avatar answered Oct 08 '22 04:10

JEzu


iOS 8 introduces the maskView property which allows you to use an alternate view to provide the mask image. In Swift:

if let maskImage = UIImage(named: "MaskImage") {     myView.maskView = UIImageView(image: maskImage) } 

Note that you need to supply an image which actually has transparency; an image with white parts (for opaque) and black parts (for transparent) won't work.

like image 37
Robert Avatar answered Oct 08 '22 02:10

Robert