2011-12-07 18 views
6

Desidero creare un'immagine combinata con due immagini diverse sovrapponendole.Come utilizzare Canvas per unire due immagini in Android?

Per questo il mio codice è

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); 

overlay() metodo è

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; 
} 
} 

caso 1: Metodo di sovrapposizione restituisce null in questo caso.

caso 2: Ma quando cambio le immagini come uso l'immagine di sfondo per l'impostazione in primo piano e in primo piano per l'impostazione in background, il codice funziona correttamente.

ma voglio che il primo caso funzioni correttamente ma non lo è. Non capisco perché questo sta accadendo.

Please Help

+0

Non so perché n come, Ora funziona. – AB1209

risposta

10

penso che accada, perché il 2 ° bitmap è più grande in termini di dimensioni. Quindi prova questo:

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

Grazie sta funzionando ora. – AB1209

+1

@Caner: funziona come un fascino !! Grazie. – dakshbhatt21