美文网首页
iOS笔记-图片两边拉伸,中间保持不变

iOS笔记-图片两边拉伸,中间保持不变

作者: chaoyk | 来源:发表于2016-08-23 20:04 被阅读0次

      今天开发过程中遇到了图片拉伸的问题。 一般情况下

    - (UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode

    下面上效果图与切图。

    效果图 切图

    来说一下我处理这个图片的方法。

    1.先拉伸菱形左边,保持右边不变。

    2.改变图片的Size。

    3.拉伸图片右边。

    用到的拉伸图片的方法

    - (UIImage*)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

    //可拉伸的范围都是距离leftCapWidth后的1竖排像素,和距离topCapHeight后的1横排像素

    先初始化一个imageView

    UIImageView*imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];

    第一步 拉伸图片左边

    UIImage*image = [UIImageimageNamed:@"xxx"];

    // 因为是距离leftCapWidth后的1竖排像素,所以可以把leftCapWidth设置为0

    // 菱形的高度为10px,所以我们要在菱形下面拉伸这个图片。

    image = [image stretchableImageWithLeftCapWidth:0 topCapHeight:5]

    这样拉伸完以后 图片会变成-------------- ◇ - 这个样子

    第二步 改变图片的size

    // 获取imageView的宽度

    CGFloat iamgeViewWidth = CGRectGetWidth(iamgeView.frame);

    // 这里imageWidth是切图的宽度

    CGFloat imageWidth = 20;

    // 图片的高度

    CGFloat imageHeight = CGRectGetHeight(iamgeView.frame);

    // 如果需要菱形居中显示的话,改变完以后的图片的宽度应该是imageView宽度的1/2加上原图宽度的1/2,这样拉伸右边的话,菱形永远居中

    CGFloat tempWidth = (iamgeViewWidth + imageWidth) / 2.0f;

    // 重新绘制Image

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tempWidth,imageHeight),NO, [UIScreenmainScreen].scale);

    [image drawInRect:CGRectMake(0,0, tempWidth,imageHeight)];

    UIImage * newImage =UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext(); 

    第三部 拉伸图片右边

    // leftCapWidth设置为新图的宽度减去1px,就会新图拉伸最右边的1px的图片填充整个imageView

    iamgeView.image= [newImage stretchableImageWithLeftCapWidth:tempWidth -0.5 topCapHeight:5];

    这是我暂时想到的拉伸两边中间不变的办法,如果哪位朋友有更好的办法,欢迎留言或者私信。

    相关文章

      网友评论

          本文标题:iOS笔记-图片两边拉伸,中间保持不变

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