美文网首页
iOS图片的拉伸

iOS图片的拉伸

作者: 搬砖行家 | 来源:发表于2020-04-10 15:32 被阅读0次

    在iOS中当UI设计的图片满足不了现有需求的时候,比如聊天框、按钮背景在图片大小达不到渲染大小的时候,这个时候就需要你对图片进行拉伸处理了。


    chat.png
    buttongreen.png

    上面两个图片尺寸分别为64x56 和 193x81。如下代码:

    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chat"]];
    imageV.frame = CGRectMake(100, 100, 300, 200);
    [self.view addSubview:imageV];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 400, 200, 200);
    [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    

    对图片和按钮分别不根据图片的尺寸和比例进行设置 渲染结果:


    渲染结果.png

    chat图片严重失真,buttongreem图片在按钮渲染上也会失真;

    对图片拉伸

    UIImage *image = [UIImage imageNamed:@"chat"];
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    
    ///分别对图片的 top left bottom right 进行拉伸
    UIImage *resizImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH/2, imageW/2,imageH/2, imageW/2)];
    
    UIImageView *imageV = [[UIImageView alloc] initWithImage:resizImage];
    imageV.frame = CGRectMake(100, 100, 300, 200);
    [self.view addSubview:imageV];
    
    UIImage *bimage = [UIImage imageNamed:@"buttongreen"];
    ///分别对图片的 水平 和 垂直 20像素进行拉伸
    UIImage *resizBImage = [bimage stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 400, 200, 200);
    [button setBackgroundImage:resizBImage forState:UIControlStateNormal];
    [self.view addSubview:button];
    

    渲染结果:


    拉伸结果

    demo已上传GitHub https://github.com/ShawnWang1/ImageResizing.git

    相关文章

      网友评论

          本文标题:iOS图片的拉伸

          本文链接:https://www.haomeiwen.com/subject/jnrrmhtx.html