gpt4 book ai didi

android - 如何居中对齐位图?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:18 24 4
gpt4 key购买 nike

我希望我的位图位于屏幕中央..我正在尝试这样做但它不起作用...

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com