swift
extension UIImage{
convenience init?(view:UIView,frame:CGRect = CGRect(x:0, y:0, width:0 , height:0)) {
let scale = UIScreen.main.scale
let newFrame = frame.scale(Int(scale))
UIGraphicsBeginImageContextWithOptions(newFrame.size, true, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
view.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
// 这里是重点, 意思是取范围内的cgimage
let cgImage = (image?.cgImage)!.cropping(to: newFrame)
self.init(cgImage:cgImage!)
}
}
extension CGRect{
public func scale(_ scale:Int) -> CGRect{
var rect = self
rect.width = self.width * CGFloat(scale)
rect.height = self.height * CGFloat(scale)
rect.x = self.x * CGFloat(scale)
rect.y = self.y * CGFloat(scale)
return rect
}
}
oc
@implementation UIImage (image)
+ (instancetype)imageWithView:(UIView *)view frame:(CGRect)frame{
int scale = [UIScreen mainScreen].scale;
CGRect rect = frame;
rect.origin.x *= scale;
rect.origin.y *= scale;
rect.size.width *= scale;
rect.size.height *= scale;
UIGraphicsBeginImageContextWithOptions(rect.size, YES, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (!context) {
return nil;
}
[view.layer renderInContext:context];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
// 这里是重点, 意思是取范围内的cgimage
CGImageRef cgImage = CGImageCreateWithImageInRect(image.CGImage, rect);
UIImage * newImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return newImage;
}
@end
这种方法比较耗时,如果谁有更好的办法,还望告知 谢谢!