奇怪的CGImage创建问题

问题描述

| 从iPhone上的原始数据创建CGImageRef时遇到一个非常奇怪的问题。我正在尝试从Perlin噪声生成函数创建CGImageRef,该函数接受x,y,z和t并返回介于-1和1之间的值。对于每个像素,我得到的噪声值介于-1和1之间,将此转换为0到255之间的char,并以以下方式从数据中创建CGImageRef ...
int width = (int)frame.size.width;
int height = (int)frame.size.height;
char* rgba = (char*)malloc(width * height * 4);

//set pixel data
int i = 0;
for(float x = 0.0; x < width; x+=1.0) {
    for (float y = 0.0; y < height; y+=1.0) {
        float perlinF = ABS([perlinGenerator perlinNoiseX:x y:y z:0.0 t:0.0]);
        char perlin = (char)( perlinF * 255.0 );

        rgba[4*i] = perlin;
        rgba[4*i+1] = perlin;
        rgba[4*i+2] = perlin;
        rgba[4*i+3] = 255;
        i++;
    }
}

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext = CGBitmapContextCreate(
                                                   rgba,width,height,8,// bitsPerComponent
                                                   4*width,// bytesPerRow
                                                   colorSpace,kCGImageAlphaNoneSkipLast);

CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
然后,如果将此CGImageRef绘制到CALayer,则会得到以下结果... 水平伪影是由我的屏幕截图创建的(不在实际图像中),但是将图像分成3个相同部分的两条垂直线是问题所在!是什么导致图像在重复3次并具有这2个垂直不连续点?甚至更奇怪的是,如果我在不创建CGImageRef的情况下手动渲染perlin噪点,就像这样...
for (CGFloat x = 0.0; x<size.width; x+=1.0) {
    for (CGFloat y=0.0; y< size.height; y+=1.0) {
        float perlinF = ABS([perlinGenerator perlinNoiseX:x y:y z:0.0 t:0.0]);
        char perlin = (char)( perlinF * 255.0 );

        CGContextSetRGBFillColor(context,1.0,(float)perlin / 255.0);
        CGContextFillRect(context,CGRectMake(x,y,1.0));
    }
}
注意,我故意将其强制转换为char,然后除以255.0,以确保强制转换为char不会引起问题。无论如何,我得到以下结果... 因此,您似乎在上述两种方法中都产生了完全相同的噪声,并且甚至从每个方法中并排打印了值以确认它们相同!因此,以某种方式从数据中创建CGImageRef而不是将其直接绘制到上下文会产生奇怪的视觉问题,这些问题会破坏图像。我需要能够在应用程序启动时生成一系列这些图像,并且不能手动绘制它们以获得良好的结果。任何人都知道什么会导致此类问题吗???     

解决方法

        由于CGBitmapContextCreate假定您的图像缓冲区是按行而不是按列索引的,因此需要将x和y换成循环。
int i = 0;
for (float y = 0.0; y < height; y+=1.0) {
    for(float x = 0.0; x < width; x+=1.0) {
        float perlinF = ABS([perlinGenerator perlinNoiseX:x y:y z:0.0 t:0.0]);
        char perlin = (char)( perlinF * 255.0 );

        rgba[4*i] = perlin;
        rgba[4*i+1] = perlin;
        rgba[4*i+2] = perlin;
        rgba[4*i+3] = 255;
        i++;
    }
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...