view生成image 支持透明背景

2,212 阅读1分钟
- (UIImage *)makeImageWithView:(UIView *)orgView withSize:(CGSize)size{
    CGFloat scale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(orgView.bounds.size, NO, scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    [orgView.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //把像素rect 转化为点rect(如无转化则按原图像素取部分图片)
    CGFloat x= orgView.frame.origin.x*scale,y=orgView.frame.origin.y*scale,w=orgView.frame.size.width*scale,h=orgView.frame.size.height*scale;
    CGRect dianRect = CGRectMake(x, y, w, h);
    //截取部分图片并生成新图片
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:scale orientation:UIImageOrientationUp];
    return newImage;
}