简体   繁体   中英

How to position bitmap using drawBitmap in android canvas

I want to position two bitmaps next to each other using drawBitmap() in Canvas, Android.

My onDraw() function.

protected void onDraw(Canvas canvas) {

    if (currentState == openedState) { 
            fruit1Bitmap = ApplicationServices.textureManager.bitmap[fruitId[0]];
            fruit2Bitmap = ApplicationServices.textureManager.bitmap[fruitId[1]];
            fruit3Bitmap = ApplicationServices.textureManager.bitmap[fruitId[2]];
            src.set(0, 0, fruit1Bitmap.getWidth(), fruit1Bitmap.getHeight());
            dst.set(0,0, this.getWidth()/2, this.getHeight()/2);
            src1.set(0, 0, fruit2Bitmap.getWidth(), fruit2Bitmap.getHeight());
            dst1.set(fruit1Bitmap.getWidth() , 0, this.getWidth()/2, this.getHeight()/2);

            canvas.drawBitmap(fruit1Bitmap, src, dst, null);
            canvas.drawBitmap(fruit2Bitmap, src1, dst1, null);
     } 
}

It is inside the class public class Dhakkan extends ImageButton .

Current Result 在此处输入图片说明

I want to get it to show two fruits next to each other. So how do I position them within the ImageButton .

  • You calculated your second destination rectangle wrong

Instead of

dst1.set(fruit1Bitmap.getWidth() , 0, this.getWidth()/2, this.getHeight()/2);

It should be something like:

dst1.set(fruit1Bitmap.getWidth(), 
    0, 
    fruit1Bitmap.getWidth() + fruit2Bitmap.getWidth(), 
    this.getHeight()/2);

Watch out for your right coordinate. This will draw the second fruit next to the first, possibly cropping it if it's too large. If you want to draw both fruits in the first half of the image button instead, then fix the coordinates of dst , the destination rectangle of the first fruit. You might also consider the method suggested by Kim.

How about reading the docs:

drawBitmap(Bitmap bitmap, float left, float top, Paint paint)

Draw the specified bitmap, with its top/left corner at (x,y), using the specified paint, transformed by the current matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM