从另一个图像创建平铺的UIImage

时间:2013-08-29 07:54:07

标签: uiimage core-graphics tiling

我有一个源图像并使用此图像我想创建各种尺寸的平铺图像。

我知道我可以使用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; }

这是一种非常耗费内存的方法。是否有更优化的方法来实现这一结果?

1 个答案:

答案 0 :(得分:0)

好的,通过在CGContext中绘制图像来解决这个问题:

UIGraphicsBeginImageContext(CGSizeMake(width * numberOfColoumns, height * numberOfRows));

for (int ii = 0; ii < numberOfRows; ii++) {
    for (int jj = 0; jj < numberOfColoumns; jj++) {
        float x = jj * width;
        float y = ii * height;
        [filteredImage drawInRect:CGRectMake(x, y, width, height)];
    }
}

UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();