与drawBitmap在画布上绘制的9片图像画布、图像、drawBitmap

2023-09-06 02:57:25 作者:花样撸管冠军╮

什么是使用9片图像资源上的自定义视图的正确方法?

What is the proper way to use a 9-patch image resource on a custom view?

我在做这样的:

background = BitmapFactory.decodeResource(getResources(), R.drawable.fundo_bookshelf);
canvas.drawBitmap(background, null, new Rect(0, y, width, y+backgroundHeight), null);

fundo_bookshelf是正确的9片图像,保存为fundo_bookshelf.9.png,如下所示:

fundo_bookshelf is a proper 9-patch image, saved as fundo_bookshelf.9.png, seen below:

但是用drawBitmap时,整个图像被拉长,而不是只与黑象素的顶部的部分,记载于本截图:

But when using the drawBitmap, the whole image is stretched, instead of only the part with the black pixel on the top, as shown on this screenshot:

推荐答案

这样的事情?

NinePatchDrawable bg =  (NinePatchDrawable) resources.getDrawable(id);
if (bg != null) {
  bg.setBounds(0, 0, getWidth(), getHeight());
  bg.draw(canvas);
  }

(对不起,我没有它适应您的code,这是从我自己的直剪切/粘贴,但希望足以去)

(sorry I didn't adapt it to your code, that is a straight cut/paste from my own, but hopefully enough to go on)