iOS-CoreGraphics学习(彩色图片转灰白图片)

CoreGraphics的功能非常强大,可以绘制出各种图形,其中,强大的核心动画 Core Animation 都是基于 CoreGraphics 实现的;

这里写图片描述


利用 CoreGraphics 将彩色图片转灰白图片事例

原始图片

这里写图片描述

转化为灰色图片

这里写图片描述


核心代码
/**
 *  普通图片转位灰白图片
 *
 *  @param image 普通图片
 *
 *  @return 灰白图片
 */
- (UIImage *)grayImage:(UIImage *)image{

    int width  = image.size.width;
    int height = image.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    CGContextRef context = CGBitmapContextCreate(nil,
                                                 width,
                                                 height,
                                                 8, // bits per component
                                                 0,
                                                 colorSpace,
                                                 kCGBitmapByteOrderDefault);

    CGColorSpaceRelease(colorSpace);

    if (context == NULL) {

        return nil;
    }

    CGContextDrawImage(context,
                       CGRectMake(0, 0, width, height), image.CGImage);
    CGImageRef imageRef   = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:imageRef];
    CFRelease(imageRef);
    CGContextRelease(context);

    return grayImage;
}

方法的调用和显示图片
- (void)viewDidLoad {
    [super viewDidLoad];
    // 获得普通图片
    UIImage *image = [UIImage imageNamed:iamgeName];
#pragma mark ----------------------------------------
    // 调用 方法将普通图片转换为灰白图片
    UIImage *grayImage = [self grayImage:image];
#pragma mark ----------------------------------------
    // 将 image 添加到 imageView 中
    UIImageView *imageView = [[UIImageView alloc] initWithImage:grayImage];
    // 根据图片宽度进行等比缩放适应屏幕的宽度
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    // 显示大小等于屏幕的大小
    imageView.frame = self.view.bounds;

    [self.view addSubview:imageView];
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值