0

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

我知道我可以在视图上实现这一点,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; }

结果证明这是一种非常占用内存的方法。有没有更优化的方法来实现这个结果?

4

1 回答 1

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();
于 2013-09-05T11:14:49.437 回答