Processing中PImage背景色设置不生效问题(已解决附说明)
Processing PImage绘制线条背景异常问题解决
我正在学习Ira Greenberg原版《Processing:创意编程与计算艺术》,在第195页有一个用PImage类通过像素绘制线条的示例。这段代码没用到setup和draw函数,逻辑很简洁。我本来想实现白色背景+黑色线条的效果,但调用background(255)后背景还是黑色,达不到预期;反而把线条颜色改成白色、保持背景黑色才能正常显示效果。我没在网上找到相关参考示例,以下是修改了第5、9、10行的代码:
/* program: p195_lines_with_pixels.pde This program shows how to create lines with pixels. This seems like it has been covered. However, this program uses the PImage library. */ size(500, 300); background(255); // 未按预期生效 // 用于计算对角线斜率 float slope = float(height)/float(width); PImage img = createImage(width, height, RGB); //color c = color(0, 0, 0); // 原代码 color c = color(255, 255, 255); // 这样能显示但颜色是反转的,我不清楚原因 // 水平线 for(int i=0; i<width; i++){ img.set(i, height/2, c); } // 垂直线 for(int i=0; i<height; i++){ img.set(width/2, i, c); } // 对角线(左上到右下) for(float i=0; i<width; i++){ img.set(int(i), int(i*slope), c); } // 对角线(左下到右上) for(float i=0; i<width; i++){ img.set(int(i), int(height-i*slope), c); } image(img, 0, 0);
问题原因
createImage()创建的PImage对象默认所有像素都是黑色(值为0),而你最后调用image(img, 0, 0)时,是把这个全黑的PImage覆盖在了之前用background(255)绘制的白色画布上。因为PImage的非线条区域都是黑色,完全盖住了下方的白色背景,所以你看不到background(255)的效果。
解决方法
方法一:给PImage设置白色背景
在创建PImage后,先将其所有像素填充为白色,再绘制黑色线条:
/* program: p195_lines_with_pixels.pde 修复后:白色背景+黑色线条 */ size(500, 300); float slope = float(height)/float(width); PImage img = createImage(width, height, RGB); // 先把PImage背景设为白色 img.loadPixels(); for (int i = 0; i < img.pixels.length; i++) { img.pixels[i] = color(255); } img.updatePixels(); color c = color(0, 0, 0); // 黑色线条 // 水平线 for(int i=0; i<width; i++){ img.set(i, height/2, c); } // 垂直线 for(int i=0; i<height; i++){ img.set(width/2, i, c); } // 对角线(左上到右下) for(float i=0; i<width; i++){ img.set(int(i), int(i*slope), c); } // 对角线(左下到右上) for(float i=0; i<width; i++){ img.set(int(i), int(height-i*slope), c); } image(img, 0, 0);
方法二:直接在主画布绘制(无需PImage)
如果不需要保留PImage对象,可直接使用Processing的全局set()函数在主画布上绘制,这样background(255)的白色背景会直接生效:
/* program: p195_lines_with_pixels.pde 简化版:直接在主画布绘制线条 */ size(500, 300); background(255); // 白色背景正常显示 float slope = float(height)/float(width); color c = color(0, 0, 0); // 黑色线条 // 水平线 for(int i=0; i<width; i++){ set(i, height/2, c); } // 垂直线 for(int i=0; i<height; i++){ set(width/2, i, c); } // 对角线(左上到右下) for(float i=0; i<width; i++){ set(int(i), int(i*slope), c); } // 对角线(左下到右上) for(float i=0; i<width; i++){ set(int(i), int(height-i*slope), c); }
内容的提问来源于stack exchange,提问作者playinmyblues
相关产品推荐
相关产品推荐

