iOS开发技巧(系列四-图片拉伸)

咱们能够经过[cell setBackgroundView:[[UIImageView alloc] initWithImage:@"xxx"]];方法设置背景,假设有一张图片名称为cell_background.png,咱们用它做为cell背景图片,app

//前面是一张图片,不信你拖动鼠标看看this

直接使用[cell setBackgroundView:[[UIImageView alloc] initWithImage:@"cell_background"]], 那么显示的时候是比较奇怪的样子,代码以下,spa

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath3d

{orm

    //...
对象

    //关键代码
图片

    cell.backgroundColor = [UIColor clearColor];it

    UIImage *cellBackImage = [UIImage imageNamed:@"cell_background"];io

    [cell setBackgroundView:[[UIImageView alloc] initWithImage:cellBackImage]];table

    //....

}

效果以下图,

图片由于拉伸,边缘都模糊了,这不是咱们想要的结果和效果。

咱们使用UIImage对象的方法,来保持边缘地方不变,而只是拉伸中间的区域,这样图片就不会模糊了,修改的代码以下,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    //..

    cell.backgroundColor = [UIColor clearColor];

    UIImage *cellBackImage = [UIImage imageNamed:@"cell_background"];

    //这里是关键代码

    cellBackImage = [cellBackImage resizableImageWithCapInsets:UIEdgeInsetsMake(15, 320, 14, 0)];//(top,left,bottom,right)

    [cell setBackgroundView:[[UIImageView alloc] initWithImage:cellBackImage]];

    //...

}

咱们看一下resizableImageWithCapInsets方法以及它的参数UIEdgeInset

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); // create a resizable version of this image. the interior is tiled when drawn.


UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {

    UIEdgeInsets insets = {top, left, bottom, right};

    return insets;

}

这个就是设置要保留的边缘,这样更改代码之后,咱们的效果图以下,

这样就显得正常了,看起来也舒服多了吧?

PS:最近在看一些完整的开源代码,例如Code4app上面的“内涵糗事”,其实看了别人的代码,能够忽然有种想通了得感受。上面的这个例子就是我本身在开源代码上面看见的一个细节,把抽象出来与你们共享。

相关文章
相关标签/搜索