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

本文介绍如何正确地为UITableViewCell设置背景图片,避免图片拉伸导致的模糊问题,并提供了一个具体的代码示例。

我们可以通过[cell setBackgroundView:[[UIImageView alloc] initWithImage:@"xxx"]];方法设置背景,假设有一张图片名称为cell_background.png,我们用它作为cell背景图片,

170432_hLgZ_1458418.png//前面是一张图片,不信你拖动鼠标看看

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

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

{

    //...

    //关键代码

    cell.backgroundColor = [UIColor clearColor];

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

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

    //....

}

效果如下图,

172306_iNA9_1458418.png

图片因为拉伸,边缘都模糊了,这不是我们想要的结果和效果。

我们使用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;

}

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

102818_LSqp_1458418.png

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

PS:最近在看一些完整的开源代码,例如Code4app上面的“内涵糗事”,其实看了别人的代码,可以突然有种想通了得感觉。上面的这个例子就是我自己在开源代码上面看见的一个细节,把抽象出来与大家共享。

转载于:https://my.oschina.net/leejan97/blog/221211

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值