2013-08-29 53 views
0

我有一個源圖像並使用它我想要創建各種大小的平鋪圖像。從另一個圖像創建平鋪的UIImage

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

事實證明,這是一個非常記憶密集的方法。有沒有一個更優化的方式來實現這個結果?

回答

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(); 
相關問題