<iOS UI基础一>图片拉伸问题

2017-08-30  本文已影响95人  Dosun

处理图片拉伸问题,有三种方案,二种是代码形式,一种是直接处理图片问题,如下图片是没有处理拉伸问题的。

Snip20170830_2.png

方式一

如下主要是用到 - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets 方法,一定给赋值的 UIImage 图片对象进行处理,我之前是将图片赋值给 UIImageView ,然后将 UIImageView 的 image 属性进行赋值,发现不行。


#import "ViewController.h"

#define WIDTH self.testImage.size.width * 0.5
#define HIEGHT self.testImage.size.height * 0.5

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *backImageView;

@property(nonatomic,strong) UIImage *testImage;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.testImage = [UIImage imageNamed:@"chat_send_nor"];
    // Do any additional setup after loading the view, typically from a nib.
    [self dealWithPictureOne];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated
}
#pragma mark - privare Method

-(void)dealWithPictureOne{
   UIImage *image =  [self.testImage resizableImageWithCapInsets:UIEdgeInsetsMake(HIEGHT - 1, WIDTH - 1, HIEGHT - 1, WIDTH -1)];

    self.backImageView.image = image;
}

方式二

主要使用 stretchableImageWithLeftCapWidth 方法,其中两个参数是,leftCapWidth 和 topCapHeight。如果 leftCapWidth 是图片宽度的一半,系统默认 right cap 是 图片宽度的一半 - 1;同理 topCapHeight如果图片高度的一半时,bottom cap 也是图片高度一半 -1 ;


- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight ;
@property(nonatomic,readonly) NSInteger leftCapWidth ;   // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
@property(nonatomic,readonly) NSInteger topCapHeight ;   // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1

代码如下

-(void)dealWithPictureTwo{
    UIImage *image = [self.testImage stretchableImageWithLeftCapWidth:WIDTH topCapHeight:HIEGHT];
    self.backImageView.image = image;

}

方式三、处理图片

Snip20170830_4.png Snip20170830_5.png

以上三个方案的效果图片

Snip20170830_7.png

四、总结

方案一,处理图片有二种模式, UIImageResizingModeTile, 平铺
UIImageResizingModeStretch, 拉伸(伸缩),一般系统是默认是平铺。开发中经常用到图片处理,如是乎弄一个 Category 类,代码如下:

#import "UIImage+OLIImageExtension.h"

@implementation UIImage (OLIImageExtension)

+(UIImage*)stretchableImageWithLocalImageName:(NSString*)imageName{
    
    UIImage *image = [UIImage imageNamed:imageName];
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    image = [image stretchableImageWithLeftCapWidth:imageWidth * 0.5 topCapHeight:imageHeight * 0.5];
    
    return image;

}
@end

上一篇 下一篇

猜你喜欢

热点阅读