6
votes

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.

3

3 Answers

4
votes

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.

1
votes

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
}
0
votes

I believe masking the image is the best option. But if you were to rotate, transform, animate or want a clear background you can do something like this:

Create a sub view which is the size of the image you want to show. Make sure it has clipsToBounds to true and position the image accordingly.

UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];

//this is the part of the image you wish to see
UIView *imageWindow = [[UIView alloc] initWithFrame:CGRectMake(30, 0, 30, 30)];
imageWindow.clipsToBounds = YES;

//your image view is the height and width of mainView and x and y is imageWindow - mainView. You can do this manually or put in calculations.
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageWindow.frame.origin.x - mainView.frame.origin.x, imageWindow.frame.origin.y - mainView.frame.origin.y, mainView.frame.size.width, mainView.frame.size.height)];
myImage.image = [UIImage imageNamed:@"1024x1024.png"];

[imageWindow addSubview:myImage];
[mainView addSubview:imageWindow];
[self.view addSubview:mainView];

Looking over my code, I don't think mainView is necessary and you could add imageWindow to self.view directly.