如何在 android canvas 中使用 drawBitmap 定位位图

How to position bitmap using drawBitmap in android canvas

我想在 Canvas、Android.

中使用 drawBitmap() 将两个位图并排放置

我的 onDraw() 函数。

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

里面是classpublic class Dhakkan extends ImageButton.

当前结果

我想让它显示两个相邻的水果。那么如何将它们定位在 ImageButton.

阅读文档如何:

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

绘制指定的位图,其 top/left 角位于 (x,y),使用指定的绘制,由当前矩阵变换。

  • 您计算的第二个目标矩形有误

而不是

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

应该是这样的:

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

注意你的正确坐标。这会将第二个水果绘制在第一个旁边,如果它太大,可能会裁剪它。如果您想在图像按钮的前半部分绘制两个水果,则固定第一个水果的目标矩形 dst 的坐标。您也可以考虑 Kim 建议的方法。