在iOS中以编程方式创建渐变图像 [英] Create gradient image programmatically in iOS

查看:110
本文介绍了在iOS中以编程方式创建渐变图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理一些直接来自设备相机的图像数据。为了理解CGImage结构,我使用缓冲区来创建一个不适合我的图像(我知道我不应该在Obj-C代码中使用C代码,它只是为了理解)。代码如下:

I'm trying to process some imagedata which comes directly from the device camera. In order to understand the CGImage structure, I'm using a buffer to create an image which doesn't work right for me (I know that I shouldn't use C code within Obj-C Code, it's just for understanding). The code is as follows:

int *outBuf = malloc(sizeof(int) * width * height);
for (int i = 0; i < width * height;i ++)
{
     outBuf[i] = (((float)i) / ((float) width * height)) * 255.f;
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

CGContextRef ctx = CGBitmapContextCreate(outBuf, width, height, 8, width * 4, colorSpace, kCGImageAlphaNone);

CGImageRef img = CGBitmapContextCreateImage(ctx);
CFRelease(ref);
CGContextRelease(ctx);
free(outBuf);

CGColorSpaceRelease(colorSpace);

[view.imgView setImage: [UIImage imageWithCGImage:img]];

CGImageRelease(img);

这应该创建从第一个像素到最后一个像素的渐变,但它会产生一个奇怪的graphic:

This should create a gradient from the very first to the very last pixel, but it results in a weird graphic:

水平间距来自哪里? (我想解决这个问题,我知道还有其他可能来绘制渐变)在此先感谢。

Where do the horizontal spacings come from? (I want to solve this issue, I'm aware that there are other possibilities to draw the gradient) Thanks in advance.

推荐答案

我找到了解决方案:

我用int *初始化缓冲区。每个int长4个字节,但灰度图片每个像素只需要1个字节。将缓冲区更改为char *并修改CGBitmapContextCreate参数修复了问题:

I was initialising the buffer with int*. Every int is 4 bytes long, but a grayscale picture just needs 1 byte per pixel. Changing the buffer to char* and modifying the CGBitmapContextCreate parameters fixed the issue:

CGBitmapContextCreate(outBuf, width, height, 8, width, colorSpace, kCGImageAlphaNone);

这篇关于在iOS中以编程方式创建渐变图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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