1. 从UIView中获取图像相当于窗口截屏。
(ios提供全局的全屏截屏函数UIGetScreenView(). 如果需要特定区域的图像,可以crop一下)
-
CGImageRef screen = UIGetScreenImage();
-
UIImage* image = [UIImage imageWithCGImage:screen];
2. 对于特定UIView的截屏。
(可以把当前View的layer,输出到一个ImageContext中,然后利用这个ImageContext得到UIImage)
-
-(UIImage*)captureView: (UIView *)theView
-
{
-
CGRect rect = theView.frame;
-
UIGraphicsBeginImageContext(rect.size);
-
CGContextRef context =UIGraphicsGetCurrentContext();
-
[theView.layer renderInContext:context];
-
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
-
UIGraphicsEndImageContext();
-
return img;
-
}
3. 如果需要裁剪指定区域。
(可以path & clip,以下例子是建一个200x200的图像上下文,再截取出左上角)
-
UIGraphicsBeginImageContext(CGMakeSize(200,200));
-
CGContextRefcontext=UIGraphicsGetCurrentContext();
-
UIGraphicsPushContext(context);
-
// …把图写到context中,省略[indent]CGContextBeginPath();
-
CGContextAddRect(CGMakeRect(0,0,100,100));
-
CGContextClosePath