UIImage的简单封装

1、颜色转图片

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

2、裁剪

#import 

@interface UIImage (Image)
+ (UIImage *)imageWithClipImage:(UIImage *)image borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)color;
@end
#import "UIImage+Image.h"

@implementation UIImage (Image)
+ (UIImage *)imageWithClipImage:(UIImage *)image borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)color {
    // 图片的宽度和高度
    CGFloat imageWH = image.size.width;
    // 设置圆环的宽度
    CGFloat border = borderWidth;
    // 圆形的宽度和高度
    CGFloat ovalWH = imageWH + 2 * border;
    // 1.开启上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(ovalWH, ovalWH), NO, 0);
    // 2.画大圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, ovalWH, ovalWH)];
    [color set];
    [path fill];
    // 3.设置裁剪区域
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(border, border, imageWH, imageWH)];
    [clipPath addClip];
    // 4.绘制图片
    [image drawAtPoint:CGPointMake(border, border)];
    // 5.获取图片
    UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
    // 6.关闭上下文
    UIGraphicsEndImageContext();
    return clipImage;
}
@end

3、截屏

//.h
// 控件截屏
+ (UIImage *)imageWithCaputureView:(UIView *)view;
+ (UIImage *)imageWithCaputureView:(UIView *)view
{
    // 开启位图上下文
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);

    // 获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 把控件上的图层渲染到上下文,layer只能渲染
    [view.layer renderInContext:ctx];

    // 生成一张图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 关闭上下文
    UIGraphicsEndImageContext();

    return image;
}

   转载规则


《UIImage的简单封装》 刘星星 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
iOS开发调试常见错误总结 iOS开发调试常见错误总结
1、bitcode: 解决办法:2、ShareSDK各社交平台申请APPkey 的网址及申请流程汇总1、新浪微博登录异常你所访问的站点在微博认证失败,请联系XXXX: 原因很可能是sina的sso填写错误。 2、登录时跳转到新浪
2016-10-30
下一篇 
Object-C的限定符的解惑总结 Object-C的限定符的解惑总结
变量限定符ARC 为变量供了四种生命周期限定符。__strong这是默认的限定符,无需显示引入。只要有强引用指向,对象就会长时间驻留在内存 中。可以将 __strong 理解为 retain 调用的 ARC 版本。 __weak这表明引用不
2016-08-07
  目录