获取图片上某个点的颜色

#pragma mark -  获取图片某点的颜色

- (void)colorAtPixel:(CGPoint)point {

    UIImageView*imageView =self.icon;


    NSIntegerpointX =trunc(point.x);

    NSIntegerpointY =trunc(point.y);

    CGImageRefcgImage = imageView.image.CGImage;

    NSUIntegerwidth = imageView.bounds.size.width;

    NSUIntegerheight = imageView.bounds.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    intbytesPerPixel =4;

    intbytesPerRow = bytesPerPixel *1;

    NSUIntegerbitsPerComponent =8;

    unsignedcharpixelData[4] = {0,0,0,0};

    CGContextRefcontext =CGBitmapContextCreate(pixelData,

                                                 1,

                                                 1,

                                                 bitsPerComponent,

                                                 bytesPerRow,

                                                 colorSpace,

                                                 kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);

    CGColorSpaceRelease(colorSpace);

    CGContextSetBlendMode(context, kCGBlendModeCopy);


    // Draw the pixel we are interested in onto the bitmap context

    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);

    CGContextDrawImage(context,CGRectMake(0.0f,0.0f, (CGFloat)width, (CGFloat)height), cgImage);

    CGContextRelease(context);


    // 把[0,255]的颜色值映射至[0,1]区间

    CGFloatred  = (CGFloat)pixelData[0];

    CGFloatgreen = (CGFloat)pixelData[1];

    CGFloatblue  = (CGFloat)pixelData[2];

    CGFloatalpha = (CGFloat)pixelData[3];


    // 改变输入框

    self.fieldR.text= [NSStringstringWithFormat:@"%.0f", red];

    self.fieldG.text= [NSStringstringWithFormat:@"%.0f", green];

    self.fieldB.text= [NSStringstringWithFormat:@"%.0f", blue];

    self.fieldA.text= [NSStringstringWithFormat:@"%.0f", alpha];


    // 改变滑动条

    self.sliderR.value= red;

    self.sliderG.value= green;

    self.sliderB.value= blue;

    self.sliderA.value= alpha;


    [self updateUIAction];

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容