2011-12-07 29 views
6

我想要通過重疊創建具有兩個不同圖像的組合圖像。如何使用Canvas在Android中合併兩個圖像?

對於此我的代碼是

ImageView image = (ImageView) findViewById(R.id.imageView1); 
    Drawable drawableFore = getResources().getDrawable(R.drawable.foreg); 
    Drawable drawableBack = getResources().getDrawable(R.drawable.backg); 

    Bitmap bitmapFore = ((BitmapDrawable) drawableFore).getBitmap(); 
    Bitmap bitmapBack = ((BitmapDrawable) drawableBack).getBitmap(); 

    Bitmap scaledBitmapFore = Bitmap.createScaledBitmap(bitmapFore, 35, 35, true); 
    Bitmap scaledBitmapBack = Bitmap.createScaledBitmap(bitmapBack, 45, 45, true); 

    Bitmap combineImages = overlay(scaledBitmapBack, scaledBitmapFore); 

    image.setImageBitmap(combineImages); 

覆蓋()方法是

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) 
{ 
try 
{ 
    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig()); 
    Canvas canvas = new Canvas(bmOverlay); 
    canvas.drawBitmap(bmp1, new Matrix(), null); 
    canvas.drawBitmap(bmp2, 0, 0, null); 
    return bmOverlay; 
} catch (Exception e) 
{ 
    // TODO: handle exception 
    e.printStackTrace(); 
    return null; 
} 
} 

殼體1:覆蓋方法在這種情況下返回null。

案例2:但是當我切換圖像像我使用背景圖像設置前景和前景圖像設置在背景中然後代碼工作正常。

但我想第一個案件應該正常工作,但事實並非如此。 我不明白爲什麼會發生這種情況。

請幫忙

+0

我不知道爲什麼ñ如何,現在它工作。 – AB1209

回答

10

我認爲這樣會發生,因爲第二個位圖的大小更大。所以試試這個:

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) 
{ 
try 
{ 
    int maxWidth = (bmp1.getWidth() > bmp2.getWidth() ? bmp1.getWidth() : bmp2.getWidth()); 
    int maxHeight = (bmp1.getHeight() > bmp2.getHeight() ? bmp1.getHeight() : bmp2.getHeight()); 
    Bitmap bmOverlay = Bitmap.createBitmap(maxWidth, maxHeight, bmp1.getConfig()); 
    Canvas canvas = new Canvas(bmOverlay); 
    canvas.drawBitmap(bmp1, 0, 0, null); 
    canvas.drawBitmap(bmp2, 0, 0, null); 
    return bmOverlay; 

} catch (Exception e) 
{ 
    // TODO: handle exception 
    e.printStackTrace(); 
    return null; 
} 
} 
+0

感謝它現在正在工作。 – AB1209

+1

@Caner:像魅力一樣工作!謝謝。 – dakshbhatt21