首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓drawBitmap位置参数

安卓drawBitmap位置参数
EN

Stack Overflow用户
提问于 2012-07-26 19:06:30
回答 2查看 7.7K关注 0票数 3

我是android图形编程的新手。我想在我的画布中央放一个位图。因此,我使用:

代码语言:javascript
复制
public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

然后我调用我想使用的位图,

代码语言:javascript
复制
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.myBitmap);

然后我用这些来找到位图的坐标位置,

代码语言:javascript
复制
float bitmapx = (float) myBitmap.getWidth();
float bitmapy = (float) myBitmap.getHeight();

float boardPosX = (canvasx - bitmapx) / 2;
float boardPosY = (canvasy - bitmapy) / 2;

最后,我用来绘制位图,

代码语言:javascript
复制
canvas.drawBitmap(myBitmap, boardPosX, boardPosY, null);

但是,位图不在画布的中心。这有点低于我认为应该是画布中心的位置。

在onDraw()方法中获取画布的高度和宽度是否正确?知道出什么问题了吗?提前谢谢。

*编辑:

最后,我通过改变

代码语言:javascript
复制
public void onDraw(Canvas canvas) {
    float canvasx = (float) canvas.getWidth();
    float canvasy = (float) canvas.getHeight();

代码语言:javascript
复制
public void onDraw(Canvas canvas) {
    float canvasx = (float) getWidth();
    float canvasy = (float) getHeight();

然而,我不知道为什么这个改变会解决我的问题。

EN

回答 2

Stack Overflow用户

发布于 2012-07-26 19:07:38

使用以下命令:

代码语言:javascript
复制
float boardPosX = ((canvasx/2) - (bitmapx / 2));
float boardPosY = ((canvasy/2) - (bitmapy / 2));
票数 2
EN

Stack Overflow用户

发布于 2014-09-12 17:51:50

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11667923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档