以编程方式从iphone屏幕的某些部分裁剪图像

时间:2009-12-08 07:56:23

标签: objective-c iphone

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];     CGSize contextSize = CGSizeMake(320,400);     UIGraphicsBeginImageContext(self.view.bounds.size);

UIGraphicsBeginImageContext(contextSize);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *savedImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setSaveImage:savedImg];

从主屏幕中取出图像的某些部分。

在UIGraphicsBeginImageContext中我只能使用大小,有没有办法用CGRect或其他方式从屏幕的特定部分提取图像,即(x,y,320,400)这样的东西

2 个答案:

答案 0 :(得分:1)

希望这会有所帮助:

// Create new image context (retina safe)
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

// Create rect for image
CGRect rect = CGRectMake(x, y, size.width, size.height);

// Draw the image into the rect
[existingImage drawInRect:rect];

// Saving the image, ending image context
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

答案 1 :(得分:0)

这个问题实际上与其他几个问题重复,包括:How to crop the UIImage?,但由于我花了一段时间才找到解决方案,我会再次发帖。

在我寻求一个我可以更容易理解的解决方案(并用Swift编写)中,我到达了这个:

我希望能够根据宽高比从区域进行裁剪,并根据外部边界范围缩放到大小。这是我的变化:

import AVFoundation
import ImageIO

class Image {

    class func crop(image:UIImage, crop source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {

        let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
        let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))

        let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
        UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)

        let scale = max(
            targetRect.size.width / sourceRect.size.width,
            targetRect.size.height / sourceRect.size.height)

        let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
        image.drawInRect(drawRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage
    }
}

我发现有几件事令人困惑,裁剪和调整大小的问题。使用传递给drawInRect的rect的原点处理裁剪,并且缩放由size部分处理。在我的例子中,我需要将源上裁剪矩形的大小与相同宽高比的输出矩相关联。然后输出/输入比例因子,这需要应用于drawRect(传递给drawInRect)。

有一点需要注意,这种方法有效地假设您绘制的图像大于图像上下文。我没有对此进行测试,但我认为您可以使用此代码来处理裁剪/缩放,但明确将scale参数定义为上述缩放参数。默认情况下,UIKit根据屏幕分辨率应用乘数。

最后,应该注意的是,这种UIKit方法比CoreGraphics / Quartz和Core Image方法更高级,并且似乎处理图像方向问题。值得一提的是,它非常快,仅次于ImageIO,根据这篇文章:http://nshipster.com/image-resizing/

相关问题