2013-07-15 20 views
0

我面臨的一般問題是:iOS:如何獲得一張拉伸的圖像?

我有一個可拉伸的50x50 PNG。我將它拉伸至300x100。我想從擴張的圖象得到大小100×100切三個UIImages,A,B &下,在下面的圖片:

enter image description here

我試圖做這樣的:

// stretchedImage is the 50x50 UIImage, abcImageView is the 300x100 UIImageView 
UIImage *stretchedImage = [abcImageView.image stretchableImageWithLeftCapWidth:25 topCapHeight:25]; 
CGImageRef image = CGImageCreateWithImageInRect(stretchedImage.CGImage, bButton.frame); 
UIImage *result = [UIImage imageWithCGImage:image]; 
[bButton setBackgroundImage:result forState:UIControlStateSelected]; 
CGImageRelease(image); 

我想使用CGImageCreateWithImageInRect裁剪中間的100(「B」),但這是不對的,因爲stretchedImage是50x50,而不是300x100。我如何獲得300x100的圖像?如果原始圖像爲300x100,則不存在任何問題,但是我會失去可伸縮圖像的優勢。

我猜想這個問題更具概括性,問題會如此簡單:如果您將圖像縮放或拉伸到更大的圖像視圖,您如何獲得縮放/拉伸的圖像?

背景爲特定的任務,我想申請的解決方案(如果你能想出的替代解決方案):

我想實現一個UI,它類似於你看到一個在原生iPhone通話應用程序的通話過程中:包含用於靜音,揚聲器,保持等按鈕的板。其中一些是具有用於選定狀態的不同背景色的切換型按鈕。

我有兩個圖形爲整個板,非選定和選定的國家。我將兩幅圖像拉伸至所需的尺寸。對於處於選定狀態的按鈕,我想獲得一張拉伸的選定圖形。

回答

0

您應該能夠通過渲染abcImageViewUIImage

UIGraphicsBeginImageContextWithOptions(abcImageView.bounds.size, NO, 0.f); 
[abcImageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

然後要做到這一點,你可以裁剪這樣的圖像(給出cropRect):

CGImageRef cgImage = CGImageCreateWithImageInRect(image.CGImage, cropRect); 
UIImage *croppedImage = [UIImage imageWithCGImage:cgImage]; 
// Do something with the image. 
CGImageRelease(cgImage); 
+0

這是正確的,非常感謝你許多!我很抱歉,這個問題有點具體,可能不會讓您獲得很多積分,但您的答案既是很好的通用知識,也是我的問題的具體答案。 – james0n

+0

沒問題,很高興幫助:) – StatusReport