我是Android图形编程的新手。 我想在我的画布中心放置一个位图。因此,我使用:
public void onDraw(Canvas canvas) {
float canvasx = (float) canvas.getWidth();
float canvasy = (float) canvas.getHeight();
然后我调用我想要使用的位图,
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.myBitmap);
然后我通过使用
找到我的位图的坐标位置float bitmapx = (float) myBitmap.getWidth();
float bitmapy = (float) myBitmap.getHeight();
float boardPosX = (canvasx - bitmapx) / 2;
float boardPosY = (canvasy - bitmapy) / 2;
最后,我使用
绘制位图canvas.drawBitmap(myBitmap, boardPosX, boardPosY, null);
但是,位图不在画布的中心。它略低于我认为应该成为画布中心的位置。
在onDraw()方法中获取画布高度和宽度是否正确? 知道什么是错的吗? 提前谢谢。
*编辑:
最后,我通过改变
使其发挥作用public void onDraw(Canvas canvas) {
float canvasx = (float) canvas.getWidth();
float canvasy = (float) canvas.getHeight();
到
public void onDraw(Canvas canvas) {
float canvasx = (float) getWidth();
float canvasy = (float) getHeight();
但是,我不知道为什么更改解决了我的问题。
答案 0 :(得分:2)
使用此:
float boardPosX = ((canvasx/2) - (bitmapx / 2));
float boardPosY = ((canvasy/2) - (bitmapy / 2));
答案 1 :(得分:1)
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);
}