iOS:如何获得一张拉伸图像?

时间:2013-07-15 18:35:31

标签: ios objective-c

我面临的一般问题是:

我有一个可伸缩的50x50 PNG。我把它拉伸到300x100。我想从拉伸的图像中获得三个尺寸为100x100的UII图像,A,B& C如下图所示:

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就没有问题,但是我会失去可伸缩图像的优势。

我想进一步概括这个问题,问题就像这样简单:如果你将图像缩放或拉伸到更大的图像视图,你如何得到缩放/拉伸的图像?

我希望应用解决方案的特定任务的背景(如果您可以提出替代解决方案):

我正在尝试实现一个类似于您在本机iPhone呼叫应用程序中调用时看到的UI:一个包含静音,扬声器,保持等按钮的板。其中一些是具有不同的切换类型按钮选定州的背景颜色。

我有两个图形用于整个印版,用于非选定和选择状态。我将两个图像拉伸到所需的大小。对于处于选定状态的按钮,我想获得一段拉伸的选定图形。

1 个答案:

答案 0 :(得分:0)

您应该可以通过将abcImageView呈现为UIImage

来实现此目的
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);