Benja0906 Benja0906 - 3 months ago 13
iOS Question

Masking a UIImageView doesn't work

I have a

UIImageview
set up:

let picture = UIImageView(frame: imageFrame)
picture.image = UIImage(named: image)


You can see it here:



Now I want to mask it a constant size, because I's going to be random pictures with random sizes, so I've created a UIView:

let frame = CGRect(x: 0, y: CGRectGetMaxY(menuLine.frame) + HeightForSize * 0.05, width: view.bounds.width, height: HeightForSize * 0.9)
let mask = UIView(frame: frame)
mask.backgroundColor = UIColor.whiteColor()


When I just add the subview to my view it looks like this:



But when I try to mask it:

picture.maskView = mask


It looks like this, what is going wrong here?


Answer

UIImageView respects contentMode which would likely serve your purpose here easier than a mask. Set your imageView to the fixed size you want all images to fit in. If you want the image to squeeze in and show black bars if its too tall for example, use UIViewContentMode.scaleAspectFit. but more likely what will look best is UIViewContentMode.scaleAspectFill. It will maintain the aspect ratio of your image and scale until it fills the imageView box you've created. Play with the two modes and others to see their effects.

let imageView = UIImageView(image: UIImage(named: "myImage"))
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
imageView.contentMode = .scaleAspectFill

More info on various contentModes you can try here.

https://developer.apple.com/reference/uikit/uiviewcontentmode

Comments