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

最佳答案

这是您在 View 中需要的代码:

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 - 如何居中对齐位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8143321/

相关文章:

android - 在android中生成线性调频信号

android - 为什么我的 Android 设备会自行重置?

java - 用于 base64 图像的自定义 Glide ModelLoader

javascript - Android 上的 Cordova 文件 API : window. requestFileSystem 永远不会在设备上触发

Android imageView 的海拔被 TextView 遮挡

android - Android 中 su 二进制文件的 suid 标志

android - 如何在 Android 中显示倾斜图?

android - 在 LinearLayout 上设置背景图片

java - 当我使用应用程序 json 查看器打开 JSON 文件时,它为空

java - 将字符串转换为日期格式