Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a subframe of a UIView?

lets say i have a UIImageView with a frame (0,0,100,30) .that imageView was assigned an image.

whats the simplest way to show only part of the image?

for example: only what appears in points 30-60 (width) and 0-30 (height). that means that the left and right edges of the image should be hidden.

just to clarify, i don't want to move the view nor change it's size, i just want to hide a subrect of it's frame.

like image 343
David Ben Ari Avatar asked Feb 11 '13 16:02

David Ben Ari


2 Answers

You could always set a mask.

CALayer *maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor blackColor].CGColor;
maskLayer.frame = CGRectmake(30.0, 0.0, 30.0, 30.0);

view.layer.mask = maskLayer;

Masks can be any type of layer, so you could even use a CAShapeLayer for complex masks and do some really cool stuff.

like image 174
Ryan Poolos Avatar answered Nov 02 '22 16:11

Ryan Poolos


i've found this solution works for me, https://stackoverflow.com/a/39917334/3192115

func mask(withRect rect: CGRect, inverse: Bool = false) {
    let path = UIBezierPath(rect: rect)
    let maskLayer = CAShapeLayer()

    if inverse {
        path.append(UIBezierPath(rect: self.view.bounds))
        maskLayer.fillRule = kCAFillRuleEvenOdd
    }

    maskLayer.path = path.cgPath
    imageView?.layer.mask = maskLayer
}
like image 37
Rachel Avatar answered Nov 02 '22 15:11

Rachel