嘿,
我浏览了保存图像的示例,之后我只想保存屏幕的一部分。
我设法保存了从图像左上角开始的部分,但我实际上想保存屏幕的中心。
只保存图像的一部分的神奇之处在于设置具有一定大小的图形上下文,如下所示:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), YES, 5.0f);
我认为可能有一种方法可以使用 CGRect 而不是大小,但这给了我一个错误。还有其他尝试或想法吗?我是否必须检查屏幕截图的像素,获取所需的像素并从中制作新图像(这将是我能想到的那种复杂的方式,但也许有更简单的方式)?
最佳答案
要使用 C4Image 对象执行此操作,您可以将 incmiko 的答案修改为如下所示:
#import "C4Workspace.h"
@implementation C4WorkSpace{
C4Image *image;
C4Image *croppedImage;
}
-(void)setup {
image=[C4Image imageNamed:@"C4Sky.png"];
image.origin=CGPointMake(0, 20);
croppedImage = [self cropImage:image toArea:CGRectMake(150,50,100,100)];
croppedImage.origin = CGPointMake(20, 360);
[self.canvas addObjects:@[image,croppedImage]];
}
-(C4Image *)cropImage:(C4Image *)originalImage toArea:(CGRect)rect{
//grab the image scale
CGFloat scale = originalImage.UIImage.scale;
//begin an image context
UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);
//create a new context ref
CGContextRef c = UIGraphicsGetCurrentContext();
//shift BACKWARDS in both directions because this moves the image
//the area to crop shifts INTO: (0, 0, rect.size.width, rect.size.height)
CGContextTranslateCTM(c, -rect.origin.x, -rect.origin.y);
//render the original image into the context
[originalImage renderInContext:c];
//grab a UIImage from the context
UIImage *newUIImage = UIGraphicsGetImageFromCurrentImageContext();
//end the image context
UIGraphicsEndImageContext();
//create a new C4Image
C4Image *newImage = [C4Image imageWithUIImage:newUIImage];
//return the new image
return newImage;
}
@end
除了代码中的注释之外,还有其他一些事情需要注意:
{150,50}
来自图像,图像的原点位于 {20,20}
那么它看起来就像你正在裁剪 {170,70}
从 Canvas 。 C4Image
对象实际上有一个 renderInContext:
方法,因此您不必从图像的图层执行此操作。 C4Image
对象换行 UIImage
对象,这就是我们使用 UIImage
构建新对象的原因我们从当前上下文中得到的 关于ios - C4 保存图像的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19490227/