如何将中心对齐位图?

时间:2011-11-15 21:23:46

标签: android

我希望我的位图位于我的屏幕中心..我正在尝试这种方式,但它不起作用......

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

            int w = canvas.getWidth();
            int h = canvas.getHeight();

            int bw=myBitmap.getWidth();
            int bh=myBitmap.getHeight();

            int cx = w / 2;
            int cy = h / 2;

            Display d = getWindowManager().getDefaultDisplay();
            int x = d.getWidth();
            int y = d.getHeight();
            int dx = x / 2;
            int dw = y /2;
            canvas.translate(cx, cy);    
            if (mValues != null) {
                canvas.rotate(-mValues[0]);
            }  

            int centreX = (x  - bw) /2;

                int centreY = (cy - bh) /2;  
            //canvas.drawPath(mPath, mPaint);
            canvas.drawBitmap(myBitmap, centreX,centreY, null);

2 个答案:

答案 0 :(得分:10)

以下是您视图中所需的代码:

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

屏幕截图只是为了好玩:http://imgur.com/EYpMJ
(对角线不是此处发布的代码的一部分)

编辑:添加了NickT的解决方案 编辑2:将mvalues [0]更改为mAngle并使其成为条件。将2次操作除以更改为位移。如果您不需要,请删除旋转代码。

答案 1 :(得分:3)

你可以试试这个:

        int width = containerBitmap.getWidth();
        int height = containerBitmap.getHeight();
        float centerX = (width  - centeredBitmap.getWidth()) * 0.5f;
        float centerY = (height- centeredBitmap.getHeight()) * 0.5f;

您可以使用它在另一个位图的中心绘制位图。