Objective-C中UIImage的平均颜色值 [英] average color value of UIImage in Objective-C

查看:86
本文介绍了Objective-C中UIImage的平均颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要物镜c中图像的平均颜色值.我想为其创建一个颜色渐变. 有人知道吗?

I need the average color value of an image in objective c. I want to create a color gradient of it. Has anyone an idea?

推荐答案

这是我尚未测试的实验代码.

here is an experimental code that i have not tested yet.

struct pixel {
    unsigned char r, g, b, a;
};

- (UIColor*) getDominantColor:(UIImage*)image
{
    NSUInteger red = 0;
    NSUInteger green = 0;
    NSUInteger blue = 0;


    // Allocate a buffer big enough to hold all the pixels

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
    if (pixels != nil)
    {

        CGContextRef context = CGBitmapContextCreate(
                                                 (void*) pixels,
                                                 image.size.width,
                                                 image.size.height,
                                                 8,
                                                 image.size.width * 4,
                                                 CGImageGetColorSpace(image.CGImage),
                                                 kCGImageAlphaPremultipliedLast
                                                 );

        if (context != NULL)
        {
            // Draw the image in the bitmap

            CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);

            // Now that we have the image drawn in our own buffer, we can loop over the pixels to
            // process it. This simple case simply counts all pixels that have a pure red component.

            // There are probably more efficient and interesting ways to do this. But the important
            // part is that the pixels buffer can be read directly.

            NSUInteger numberOfPixels = image.size.width * image.size.height;
            for (int i=0; i<numberOfPixels; i++) {
                red += pixels[i].r;
                green += pixels[i].g;
                blue += pixels[i].b;
            }


            red /= numberOfPixels;
            green /= numberOfPixels;
            blue/= numberOfPixels;


            CGContextRelease(context);
        }

        free(pixels);
    }
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1.0f];
}

您可以使用此方法,例如;

You can use this method eg;

-(void)doSomething
{
    UIImage *image = [UIImage imageNamed:@"someImage.png"];
    UIColor *dominantColor = [self getDominantColor:image];
}

我希望这对您有用.

您还可以在带有类别的UIImage中实现.为对象编写一些实用程序的更好方法:)

Also you can implement in UIImage with category. Better way to write some utilities for objects :)

编辑:修复了while()中的错误.

这篇关于Objective-C中UIImage的平均颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆