iOS屏幕截图的一部分

yeh*_*eha 12 xcode objective-c ios

我有一个应用程序,它使用以下代码获取UIImageView的屏幕截图:

-(IBAction) screenShot: (id) sender{

 UIGraphicsBeginImageContext(sshot.frame.size);
 [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
 UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 UIImageWriteToSavedPhotosAlbum(viewImage,nil, nil, nil);


}
Run Code Online (Sandbox Code Playgroud)

这很好但我需要能够定位我截取屏幕截图的位置基本上我只需要在屏幕的三分之一处(中心部分).我试过用

UIGraphicsBeginImageContext(CGSize 150,150);
Run Code Online (Sandbox Code Playgroud)

但是已经发现每件东西都取自0,0坐标,任何人都知道如何正确定位.

Lef*_*ris 29

截图是从您绘制的画布中截取的.因此,不是在整个上下文中绘制图层,而是引用左上角,您将绘制它以获取截图的位置....

//first we will make an UIImage from your view
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *sourceImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//now we will position the image, X/Y away from top left corner to get the portion we want
UIGraphicsBeginImageContext(sshot.frame.size);
[sourceImage drawAtPoint:CGPointMake(-50, -100)];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(croppedImage,nil, nil, nil);
Run Code Online (Sandbox Code Playgroud)

  • 什么是`sshot.frame.size`?你是说`self.view.frame.size`吗? (2认同)

app*_*eak 14

这个

UIGraphicsBeginImageContext(sshot.frame.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 150, 150);    // <-- shift everything up to required position when drawing.
[self.view.layer renderInContext:c];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
Run Code Online (Sandbox Code Playgroud)


Par*_*iya 7

如果您有具有特定矩形的图像裁剪,请使用此方法进行裁剪:

-(UIImage *)cropImage:(UIImage *)image rect:(CGRect)cropRect
{
   CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
   UIImage *img = [UIImage imageWithCGImage:imageRef]; 
   CGImageRelease(imageRef);
   return img;
}
Run Code Online (Sandbox Code Playgroud)

使用这样:

UIImage *img = [self cropImage:viewImage rect:CGRectMake(150,150,100,100)]; //example
Run Code Online (Sandbox Code Playgroud)