android – 如何将中心对齐位图?

前端之家收集整理的这篇文章主要介绍了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);

解决方法

以下是您在视图中需要的代码
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次操作除以更改为位移.如果您不需要,请删除旋转代码.

原文链接:https://www.f2er.com/android/312013.html

猜你在找的Android相关文章