How to hide UIView subframe?

says that I have a UIImageView with a frame (0,0,100,30). that ImageView was assigned an image.

What is the easiest way to show only part of an image?

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

just to clarify, I don’t want to move the view or resize it, I just want to hide its correct frame.

+6
source share
3 answers

You can always set the 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 can even use CAShapeLayer for complex masks and do really cool things.

+3
source

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

Create a subview that represents the size of the image you want to display. Make sure its clipsToBounds is true and the position of the image, respectively.

 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 back at my code, I don't think that mainView necessary, and you can add imageWindow to self.view directly.

0
source

I found this solution to work for me, fooobar.com/questions/33697 / ...

 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
source

All Articles