注意:获取原图的时候,需要考虑图片的scale,否则截取的图片不对。
/// 获得某个范围内的屏幕图像 -- 原图需要考虑scale
+ (UIImage *)imageFromView:(UIView *)view atFrame:(CGRect)rect {
/// 不是高清的
// UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 1.0);
/// 高清的
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 原图的话需要考虑 scale ---- 这样就ok了,原图,并且图片正常
CGRect myImageRect = CGRectMake(rect.origin.x*image.scale, rect.origin.y*image.scale, rect.size.width*image.scale, rect.size.height*image.scale);
// 不是原图,不用考虑
// CGRect myImageRect = rect;
CGImageRef imageRef = image.CGImage;
CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef,myImageRect );
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, myImageRect, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
CGImageRelease(subImageRef);
UIGraphicsEndImageContext();
return smallImage;
}
网友评论