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;
}