2011-12-16 70 views
2

​​UIImage的另一UIImage的

的選擇部分我有一個的UIImage和CGPoint還告訴我,在什麼方向,我應該將它移動到創建另一個形象。背景可以是任何東西。

給出最初的UIImage如何創建新的UIImage?什麼是最有效的方法呢?

下面是我在做什麼:

int originalWidth = image.size.width; 
int originalHeight = image.size.height; 
float xDifference = [[coords objectAtIndex:0] floatValue]; 
float yDifference = [[coords objectAtIndex:1] floatValue]; 


UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 240, originalWidth, originalHeight)]; 

UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
imageView.contentMode = UIViewContentModeTopLeft; 

CGRect imageFrame = imageView.frame; 
imageFrame.origin.x = xDifference; 
imageFrame.origin.y = -yDifference; 
imageView.frame = imageFrame; 

UIGraphicsBeginImageContext(tempView.bounds.size); 
[tempView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

是否有更優化的版本?

回答

8

您可以使用 CGImageCreateWithImageInRect() 。您可以從UIImage property of the same name 獲得CGImage

基本上你最終要做的是將掩碼應用於現有圖像以提取你需要的部分。像這樣 -

enter image description here

myImageArea = CGRectMake(xOrigin, yOrigin, myWidth, myHeight);//newImage 
mySubimage = CGImageCreateWithImageInRect(oldImage, myImageArea); 
myRect  = CGRectMake(0, 0, myWidth*2, myHeight*2); 
CGContextDrawImage(context, myRect, mySubimage); 

This post給出瞭如何使用此屬性是一個好主意。

+0

我試過了,它沒有工作。這是幾個小時前的工作,所以我不清楚,但我不認爲這是填補形象。 – 2011-12-16 18:46:47