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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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;
    }

 

 

转载于:https://my.oschina.net/zhaodacai/blog/790661

你可能感兴趣的:(swift,python)