我有一个源图像,我想使用它来创建各种尺寸的平铺图像。
我知道我可以在视图上实现这一点,colorWithPatternImage:
但我希望输出为 UIImage。
我尝试通过首先创建所需大小的 UIView 来做到这一点:
- (UIImage *)patternImageWithImage:(UIImage *)filteredImage andSize:(PatternImageSize)size; {
int numberOfRows;
int numberOfColoumns;
if (size == PatternImageSize3x3) {
numberOfRows = 3;
numberOfColoumns = 3;
}
else
{
numberOfRows = 15;
numberOfColoumns = 15;
}
float width = filteredImage.size.width;
float height = filteredImage.size.height;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width * numberOfColoumns, height * numberOfRows)];
view.backgroundColor = [UIColor colorWithPatternImage:filteredImage];
[view.layer setOpaque:NO];
UIImage* patternImage = [self imageWithView:view];
return patternImage; }
然后从这个视图中创建一个 UIImage :
- (UIImage *)imageWithView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img; }
结果证明这是一种非常占用内存的方法。有没有更优化的方法来实现这个结果?