IOS 图片不变形显示

主要内容:

1、contentMode
2、layer contentsRect

contentMode 就是描述内容的填充模式。

typedef NS_ENUM(NSInteger, UIViewContentMode) {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
};
IOS 图片不变形显示_第1张图片
网上截图.png

contentsRect
/* A rectangle in normalized image coordinates defining the

  • subrectangle of the `contents' property that will be drawn into the
  • layer. If pixels outside the unit rectangles are requested, the edge
  • pixels of the contents image will be extended outwards. If an empty
  • rectangle is provided, the results are undefined. Defaults to the
  • unit rectangle [0 0 1 1]. Animatable. */
    在现在的图像坐标系统中,contentsRect描述了一个在layer层重画的一个子矩形。控制图层内容的显示。

在实际应用中,类似微信朋友圈,照片的显示,当显示多张图片的时候,由于我们会固定显示view 的大小为一个矩形,但是如果我们直接将照片放入会发生变形。

IOS 图片不变形显示_第2张图片
变形图片.png

但是在大多数情况下面我们都希望能够不变形。图片按照长宽来分,大概分为3种,W>H , W=H, W

例子:


1: W > H
    UIImageView  *squerImage = [[UIImageView alloc]initWithFrame:CGRectMake(30, 300, 100, 100)];
    squerImage.layer.borderColor = [UIColor redColor].CGColor;
    squerImage.layer.borderWidth = 1;
    squerImage.layer.masksToBounds = true;
    
    UIImage *widthImage = [UIImage imageNamed:@"zisehua.jpg"];
    squerImage.image = widthImage;
    squerImage.contentMode = UIViewContentModeScaleAspectFill;
    
    [self.view addSubview:squerImage];

结果:

IOS 图片不变形显示_第3张图片
W > H 显示中间.png

2: H > W

    UIImageView *qingting = [[UIImageView alloc]initWithFrame:CGRectMake(30, 430, 100, 100)];
    qingting.layer.borderColor = [UIColor redColor].CGColor;
    qingting.layer.borderWidth = 1;
    qingting.layer.masksToBounds = true;
    
    
    UIImage *qingtingImage = [UIImage imageNamed:@"qingting.jpg"];
    qingting.image = qingtingImage;
    qingting.layer.contentsRect = CGRectMake(0, 0,1, qingtingImage.size.width/qingtingImage.size.height);
    qingting.contentMode = UIViewContentModeScaleToFill;
    
    [self.view addSubview:qingting];

结果:

IOS 图片不变形显示_第4张图片
H > W 显示上面.png

你可能感兴趣的:(IOS 图片不变形显示)