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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...