2011-02-10 36 views
1

我想合併兩個UIImages,一個可伸縮和一個「正常」的。問題是,如果我使用UIGraphicsImageContext合併圖像,則第二個圖像也被拉伸(它在第一個圖像的頂部,因爲它應該是,但拉伸)。有人知道如何避免這種情況嗎?合併可伸縮UIImage與「正常」一個

非常感謝!從我的ViewController

電話:

UIImage *stretchImage = [[UIImage imageNamed:@"stretchableLeft.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:16.0]; 
    stretchImage = [self imageWithImage:stretchImage scaledToSize:CGSizeMake(64.0, 64.0)]; 
    stretchImage = [self mergeImageWithImage:stretchImage secondImage:[UIImage imageNamed:@"topImage.png"]]; // only 40x40 Px 

的兩種方法是:

- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize 
{ 
UIGraphicsBeginImageContext(newSize); 
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; 
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return newImage; 


- (UIImage*)mergeImageWithImage:(UIImage *)image secondImage:(UIImage *)image2 
{ 
UIGraphicsBeginImageContext(image.size); 
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; 
[image2 drawInRect:CGRectMake(10,10,image.size.width,image.size.height) blendMode:kCGBlendModeNormal alpha:1.0]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return newImage; 
} 

回答

1

我認爲這個問題是你問的這兩個圖像在全矩形中繪製。這是導致你的第二張圖片拉伸。

嘗試在合併圖像時使用image2的image2.size。繪製矩形時,必須使用x/y座標調整位置。

- (UIImage*)mergeImageWithImage:(UIImage *)image secondImage:(UIImage *)image2 
{ 
UIGraphicsBeginImageContext(image.size); 
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; 
[image2 drawInRect:CGRectMake(10,10,image2.size.width,image2.size.height) blendMode:kCGBlendModeNormal alpha:1.0]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return newImage; 
}