2015-08-14 56 views
0

我正在使用以下代碼在彼此之上繪製位圖。在Android上在畫布上疊加位圖

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(new MyView(this)); 
    } 

    public class MyView extends View 
    { 
     public MyView(Context context) 
     { 
      super(context); 
     } 

     @Override 
     protected void onDraw(Canvas canvas) 
     { 

      Bitmap bitmap = null; 
      Resources res = getResources(); 

      Bitmap bitmap1 = BitmapFactory.decodeResource(res, R.drawable.ic_launcher); 

      Bitmap bitmap2 = BitmapFactory.decodeResource(res, R.drawable.ic_launcher2); 

      bitmap = Bitmap.createBitmap(bitmap1.getWidth() + 200, bitmap1.getHeight() + 200, 
        Config.ARGB_8888); 

      canvas.drawBitmap(bitmap1, 0, 0, null); 

      super.onDraw(canvas); 

     } 
    } 
    } 

以下行在畫布上繪製bitmap1。

canvas.drawBitmap(bitmap1, 0, 0, null); 

但是,如果我使用下面的代碼,它不會繪製任何東西。我知道這是新的畫布,但它會在哪裏畫?

canvas = new Canvas(bitmap); // Sets background bitmap. 
    canvas.drawBitmap(bitmap1, 0, 0, null); 
    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); 
    canvas.drawBitmap(bitmap2, 0, 0, paint) 

對於現有的畫布對象,我也用canvas.setBitmap(bitmap);嘗試,但它仍然不畫任何東西。任何幫助,將不勝感激。謝謝。

+0

你爲什麼要創建一個新的'Canvas'?什麼是'c'? – tachyonflux

+0

ouch。 c是一個錯字。我編輯它來顯示畫布。我不知道如何爲背景設置「位圖」,所以我嘗試創建一個新的畫布對象。我也嘗試設置canvas.setBitmap(位圖),但它仍然沒有畫任何東西。 –

+0

我不明白你有什麼問題。 'drawBitmap'有什麼問題? – tachyonflux

回答

0

我想通了。這是人們如何做到的。我從SO複製了overlay()方法,但我忘記了參考。

@Override 
    protected void onDraw(Canvas canvas) 
    { 
     Resources res = getResources(); 
     bitmapOverlay(canvas, res); 
     super.onDraw(canvas); 
    } 


public static void bitmapOverlay(Canvas canvas, Resources res){ 
    Bitmap bitmap = null; 
    try { 

     Bitmap bitmap1 = BitmapFactory.decodeResource(res, R.drawable.ic_launcher); // blue 

     Bitmap bitmap2 = BitmapFactory.decodeResource(res, R.drawable.dashboard_icon); // green 

     Bitmap result = overlay(bitmap2, bitmap1); 
     canvas.drawBitmap(result, 300, 300, null); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) { 
    Bitmap bmOverlay = Bitmap.createBitmap(bmp2.getWidth() + 200, bmp2.getHeight() + 200, 
      bmp1.getConfig()); 
    float left = (bmp2.getWidth() - (bmp1.getWidth() * ((float) bmp2.getHeight()/(float) bmp1 
      .getHeight())))/(float) 2.0; 
    Canvas canvas = new Canvas(bmOverlay); 
    canvas.drawBitmap(bmp1, left, 0, null); 
    canvas.drawBitmap(bmp2, new Matrix(), null); 
    return bmOverlay; 
}