1

在我的应用程序中,我有一个,在此之上UIImageView有一个清晰的背景颜色。UIViewUIImageView

我正在使用UIBezierPath在此 UIView 上进行免费手绘,以便用户UIImageUIImageView.

我正在为UIBezierPath颜色添加透明度。

UIImage我的问题是,当我最初加载UIImageView如何制作UIImage灰度外观时,当用户在屏幕上移动手指时,原始颜色UIImage会显示给用户吗?

4

2 回答 2

0

正确的方法是使用 Core Image,并编写自己的 Core Image 过滤器来对彩色图像进行操作。通过在过滤器上设置一些属性,它会知道绘制一些颜色的部分,但将其他区域转换为灰度。

也就是说,这不是一个微不足道的工作项目。您也许可以一起破解其他东西,但它可能会生涩且不流畅。Core Image 过滤器的工作方式与 Core Animation 相同(在 GPU 附近),所以如果你采用这种方式,它会很好地工作。

于 2012-07-27T11:28:42.817 回答
0

触摸时,调用此函数返回灰度图像。在触摸结束时,为 UIImageView 设置原始图像。

- (UIImage*)imageWithGrayScaleImage:(UIImage*)inputImg
{   
//Creating image rectangle
//CGRect imageRect = CGRectMake(0, 0, inputImg.size.width / (CGFloat)[inputImg scale], inputImg.size.height / (CGFloat)[inputImg scale]);
CGRect imageRect = CGRectMake(0, 0, inputImg.size.width, inputImg.size.height);

//Allocating memory for pixels
int width = imageRect.size.width;
int height = imageRect.size.height;

uint32_t *pixels = (uint32_t*)malloc(width * height * sizeof(uint32_t));

//Clearing the memory to preserve any transparency.(Alpha)
memset(pixels, 0, width * height * sizeof(uint32_t));

//Creating a context with RGBA pixels
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

//Drawing the bitmap to the context which will fill the pixels memory
CGContextDrawImage(context, imageRect, [inputImg CGImage]);

//Indices as ARGB or RGBA
const int RED = 1;
const int GREEN = 2;
const int BLUE = 3;

for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        uint8_t* rgbaPixel = (uint8_t*)&pixels[y * width + x];

        //Calculating the grayScale value
        uint32_t grayPixel = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];

        //Setting the pixel to gray
        rgbaPixel[RED] = grayPixel;
        rgbaPixel[GREEN] = grayPixel;
        rgbaPixel[BLUE] = grayPixel;
    }
}

//Creating new CGImage from the context with modified pixels
CGImageRef newCGImage = CGBitmapContextCreateImage(context);

//Releasing resources to free up memory
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(pixels);

//Creating UIImage for return value
//UIImage* newUIImage = [UIImage imageWithCGImage:newCGImage scale:(CGFloat)[inputImg scale] orientation:UIImageOrientationUp];
UIImage* newUIImage = [UIImage imageWithCGImage:newCGImage];

//Releasing the CGImage
CGImageRelease(newCGImage);

return newUIImage;
}
于 2012-07-27T12:06:06.933 回答