加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift3.0截取View生成图片 图片截取成新图片

发布时间:2020-12-14 06:36:28 所属栏目:百科 来源:网络整理
导读:swift: //注意/Users/point/Desktop == point是我电脑的用户名 改成你自己的 let img1 = getImage(size: CGSize(width: 200,height: 200),currentView: view) let img2 = getImageFromImage(oldImage: img1,newImageRect: CGRect(x: 100,y: 100,width: 100,h

swift:

//注意/Users/point/Desktop == point是我电脑的用户名 改成你自己的
        let img1 = getImage(size: CGSize(width: 200,height: 200),currentView: view)
        let img2 = getImageFromImage(oldImage: img1,newImageRect: CGRect(x: 100,y: 100,width: 100,height: 100))
        let imgData = UIImageJPEGRepresentation(img2,1)
        NSData(data: imgData!).write(toFile: "/Users/point/Desktop/456.png",atomically: true)
//View生成图片
    func getImage(size:CGSize,currentView:UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions( size,true,1.0)
        currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!;
    }
    
    //图片中截取图片
    func getImageFromImage(oldImage:UIImage,newImageRect:CGRect) ->UIImage {
        let imageRef = oldImage.cgImage;
        let subImageRef = imageRef!.cropping(to: newImageRect);
        return UIImage(cgImage: subImageRef!)
    }

赠送OC版本的:

// 从view上截图
    - (UIImage *)getImage {
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(150,150),NO,1.0);  //NO,YES 控制是否透明
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // 生成后的image
    
    return image;
    }
    
    // 根据给定得图片,从其指定区域截取一张新得图片
    -(UIImage *)getImageFromImage{
    //大图bigImage
    //定义myImageRect,截图的区域
    CGRect myImageRect = CGRectMake(70,10,150,150);
    UIImage* bigImage= [UIImage imageNamed:@"mm.jpg"];
    CGImageRef imageRef = bigImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef,myImageRect);
    CGSize size;
    size.width = 150;
    size.height = 150;
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context,myImageRect,subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    return smallImage;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读