iOS实现平铺的几种简单方式

UI效果

原图为一个小圆圈,实现将该图平铺到一个较大的视图中,并保证清晰度不变。

一、colorWithPatternImage

通过iOS自带的image平铺成UIColor,可快速将UIView的backgroundColor变成图片平铺的效果,图片根据原始大小铺满View。

UIImage *originImage = [UIImage imageNamed:@"pile_icon.png"];
    UIImageView *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 350, 96, 96)];
    testImageView.backgroundColor = [UIColor colorWithPatternImage:originImage];
    [self.view addSubview:testImageView];

UIColor转Image取出平铺图

CGRect rect = CGRectMake(0, 0, 96, 96);

UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();
//取出第一步中的backgroundColor生成图片
CGContextSetFillColorWithColor(context,
                                       [testImageView.backgroundColor CGColor]);
    
CGContextFillRect(context, rect);
    //取出背景
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

二、layer.contents

通过image设置resizableImageWithCapInsets实现自适应大小方式。

UIImage *originImage = [UIImage imageNamed:@"pile_icon.png"];
UIImageView *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 350, 96, 96)];
UIImage *resizeImage = [originImage resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile];
testimageView.layer.contents = (__bridge id _Nullable)(resizeImage.CGImage);
[self.view addSubview:testImageView];

三、CGContextDrawTiledImage直接绘制

+ (UIImage *)getTileImage:(CGSize )size originImage:(UIImage *)originImage {
    
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawTiledImage(context, CGRectMake(0, 0, originImage.size.width,originImage.size.height), originImage.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值