ios 指定范围截图

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

这种方法比较耗时,如果谁有更好的办法,还望告知 谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,245评论 4 61
  • centos使用与服务器,ubuntu使用与桌面。http://www.centoscn.com/CentosSo...
    苟雨阅读 215评论 0 0
  • 悦悦乐阅读 111评论 0 0
  • 林心如和霍建华在一起了。 5.20那天,看着满屏对他们的祝福以及对胡歌的调侃,我却想到了我身边的一个姑娘,那个活得...
    唯妈养娃阅读 496评论 0 5