How to add 3 images to canvas in android

I have 3 images that I want to add one by one to the canvas. This is my code: -

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageButton im1 = (ImageButton)findViewById(R.id.btnPN); 
    im1.setBackgroundDrawable(getImage());       
}

public BitmapDrawable getImage()
{

    Drawable image1 = getResources().getDrawable(R.drawable.imagename);
    Drawable image2 = getResources().getDrawable(R.drawable.imagename);
    Drawable image3 = getResources().getDrawable(R.drawable.imagename);

    Bitmap bitmap = Bitmap.createBitmap(image1.getIntrinsicWidth()            
          +image2.getIntrinsicWidth()+image3.getIntrinsicWidth(),
          image1.getIntrinsicHeight(),Bitmap.Config.ALPHA_8);

    Canvas canvas = new Canvas(bitmap);

    image1.setBounds(0, 0, image1.getIntrinsicWidth(), image1.getIntrinsicHeight());
    image1.draw(canvas);

    image2.setBounds(image1.getIntrinsicWidth(), 0, image2.getIntrinsicWidth(),
            image2.getIntrinsicHeight());
    image2.draw(canvas);

    image3.setBounds(image1.getIntrinsicWidth()+image2.getIntrinsicWidth(),
                      0, image3.getIntrinsicWidth(),
                      image3.getIntrinsicHeight());
    image3.draw(canvas);


    BitmapDrawable bu = new BitmapDrawable(bitmap);
    return bu;    

}

but it does not work.

Can someone please tell me what I'm doing wrong here.

Thank you Fara

+3
source share
1 answer

I had to solve something similar not so long ago, and you are almost there with your decision. However, you must use Rect objects to offset where you draw a bitmap every time. Assuming you copied all of your images into an array of raster images [], and you created a raster image and canvas, as you did above, use the following:

Rect srcRect;
Rect dstRect;

for (int i = 0; i < images.length; i++){
    srcRect = new Rect(0, 0, images[i].getWidth(), images[i].getHeight());
    dstRect = new Rect(srcRect);
    if (i != 0){
        dstRect.offset(images[i-1].getWidht(), 0)
    }
    canvas.drawBitmap(images[i], srcRect, dstRect, null);
}

. , 4 - , .

+4

Source: https://habr.com/ru/post/1736288/


All Articles