UIGraphicsBeginImageContext 的一些实际应用

/// 图片的缩放裁剪
- (UIImage *)rescaleImage:(UIImage *)img ToSize:(CGSize)size;
/// 等比例缩放
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize;
/// 出来某个特定的View
- (UIImage *)captureView:(UIView *)theView;
/// 合并两张图片
+ (UIImage *)addImage:(UIImage *)image_1 toImage:(UIImage *)image_2;

具体实现如下:

- (UIImage *)rescaleImage:(UIImage *)img ToSize:(CGSize)size{
    CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    [img drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (UIImage *)captureView:(UIView *)theView{
    CGRect rect = theView.frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)addImage:(UIImage *)image_1 toImage:(UIImage *)image_2{
    UIGraphicsBeginImageContext(image_1.size);
    [image_1 drawInRect:CGRectMake(0, 0, image_1.size.width, image_1.size.height)];
    [image_2 drawInRect:CGRectMake(0, 0, image_2.size.width, image_2.size.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}

 关于UIGraphicsBeginImageContext

posted @ 2016-10-28 10:34  MaricoSun  阅读(169)  评论(0编辑  收藏  举报