How to show in UIImage just a part of image?

后端 未结 3 1130
旧巷少年郎
旧巷少年郎 2021-02-15 16:48

I have UIImageView in which I\'m showing 50x100 image.

I want to show only a part of image 50x50 (top part)?

How can I do that?

3条回答
  •  盖世英雄少女心
    2021-02-15 17:32

    The very simple way to move big image inside UIImageView as follows.

    Let we have the image of size (100, 400) representing 4 states of some picture one below another. We want to show the 2nd picture having offsetY = 100 in square UIImageView of size (100, 100). The solution is:

    UIImageView *iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    CGRect contentFrame = CGRectMake(0, 0.25, 1, 0.25);
    iView.layer.contentsRect = contentFrame;
    iView.image = [UIImage imageNamed:@"NAME"];
    

    Here contentFrame is normalized frame relative to real UIImage size. So, "0" means that we start visible part of image from left border, "0.25" means that we have vertical offset 100, "1" means that we want to show full width of the image, and finally, "0.25" means that we want to show only 1/4 part of image in height.

    Thus, in local image coordinates we show the following frame

    CGRect visibleAbsoluteFrame = CGRectMake(0*100, 0.25*400, 1*100, 0.25*400)
    or CGRectMake(0, 100, 100, 100);
    

提交回复
热议问题