2010-10-24 17 views
0

我使用以下代碼,目的是創建一個半白半黑的圖像並將其放在一個按鈕上。 我的代碼有什麼問題? (後面我們要使用什麼像素是白色的,什麼是黑的更復雜的邏輯,但它應該仍然是黑色和白色)在android中創建圖像並渲染到ImageButton中

int height = 100; 
int width = 100; 

quadratImage = Bitmap.createBitmap(
     width, 
     height, 
     Bitmap.Config.ALPHA_8); 
for (int x = 0; x < width; x++){ 
    for (int y = 0; y < height; y++){ 
     int color; 

     if (x< 50){ 

      color = R.color.black; 

     } 
     else{ 
      color = R.color.white; 
     } 

     quadratImage.setPixel(
       x, y, color); 
    } 
} 
quadratImage.prepareToDraw(); 
imageButton.setImageBitmap(quadratImage); 

我的顏色定義爲:

<color name="black">#000000</color> 
<color name="white">#ffffff</color> 
+0

您遇到的問題是什麼? – Asahi 2010-10-24 22:48:52

回答

1

一兩件事,當你直接繪製成位圖顏色的int不是顏色的資源ID,而是ARGB實際顏色值的十六進制表示(例如,0xff000000表示黑色,0xffffffff表示白色)。你也可以通過getResources()。getColor(colorResourceId)獲取這個值。另外,不是試圖逐個像素逐像素地繪製,而是學會使用Android的畫布工具 - 您可以簡單地用白色填充畫布,然後drawRect(http://developer.android.com/reference/) android/graphics/Canvas.html#drawRect(float,float,float,float,android.graphics.Paint))一個黑色矩形到屏幕的另一半。這將比嵌套循環少得多的代碼,並且系統可以使用硬件加速和其他快捷方式優化畫布繪製,而不是痛苦地逐個像素地形成整個位圖。

1

如果您想要將圖像分成4份不會起作用,您會將它分成兩半黑色,一半白色。

您需要在if(x < 50)(和其他條件)括號中進行測試,以根據y值改變顏色。

OK,您的評論指出,需要

Resources res = this.getResources(); 

以上的地方,然後

color = res.getColor(R.color.black); 

和白色

+0

這不會產生半白半黑的圖像。如果這會增加一個y條件將是微不足道的。 – Christian 2010-10-24 21:41:16