3

我是 android 图形编程的新手。我想在画布的中心放置一个位图。因此,我使用:

public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

然后我调用我想使用的位图,

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.myBitmap);

然后我使用这些找到我的位图的坐标位置,

float bitmapx = (float) myBitmap.getWidth();
float bitmapy = (float) myBitmap.getHeight();

float boardPosX = (canvasx - bitmapx) / 2;
float boardPosY = (canvasy - bitmapy) / 2;

最后,我使用绘制位图,

canvas.drawBitmap(myBitmap, boardPosX, boardPosY, null);

但是,位图不在画布的中心。它略低于我认为应该是画布中心的位置。

在 onDraw() 方法中获取画布高度和宽度是否正确?知道有什么问题吗?提前致谢。

*编辑 :

最后,我通过改变使它工作

public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

public void onDraw(Canvas canvas) {
    float canvasx = (float) getWidth();
    float canvasy = (float) getHeight();

但是,我不知道为什么更改可以解决我的问题。

4

2 回答 2

2

用这个:

float boardPosX = ((canvasx/2) - (bitmapx / 2));
float boardPosY = ((canvasy/2) - (bitmapy / 2));
于 2012-07-26T11:07:37.933 回答
1
private int mWidth;
private int mHeight;
private float mAngle;

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
    mHeight = View.MeasureSpec.getSize(heightMeasureSpec);

    setMeasuredDimension(mWidth, mHeight);
}

@Override protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
    Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);

    // Here's the magic. Whatever way you do it, the logic is:
    // space available - bitmap size and divide the result by two.
    // There must be an equal amount of pixels on both sides of the image.
    // Therefore whatever space is left after displaying the image, half goes to
    // left/up and half to right/down. The available space you get by subtracting the
    // image's width/height from the screen dimensions. Good luck.

    int cx = (mWidth - myBitmap.getWidth()) >> 1; // same as (...) / 2
    int cy = (mHeight - myBitmap.getHeight()) >> 1;

    if (mAngle > 0) {
        canvas.rotate(mAngle, mWidth >> 1, mHeight >> 1);
    }

    canvas.drawBitmap(myBitmap, cx, cy, null);
}
于 2014-09-12T09:51:50.363 回答