我的情况涉及绘制一个背景,其中其他对象包含在背景区域内,以进行边界。我设置了我的表面视图绘图以将我的位图布局在正确的位置,但是当我在不同的设备上进行测试时,事情不在正确的位置。
我将我的代码重构为不那么具体,并将我的所有计算都基于画布的中心(这是我给定图像的要求)。鉴于我的其他对象必须保留在图像的特定区域,我认为我可以找出 mdpi 图像上的 xy 位置并尝试根据画布的比例缩放我的位置。没用。在这一点上,我真的不确定还有什么可以尝试的。
//Center of canvas
float centerX = canvas.getWidth() / 2;
float centerY = canvas.getHeight() / 2;
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mBackground.getWidth() / 2), -(mBackground.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX, centerY);
canvas.drawBitmap(mBackground, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mFlatBobble.getWidth() / 2), -(mFlatBobble.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX-(10 * mScale), centerY + (50 * mScale));
canvas.drawBitmap(mFlatBobble, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mBobble.getWidth() / 2), -(mBobble.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX + (68 * mScale), centerY + (78 * mScale));
canvas.drawBitmap(mBobble, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mMask.getWidth() / 2), -(mMask.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX, centerY);
canvas.drawBitmap(mMask, mDrawingMatrix, null);
EDIT2:下面的代码已过时。请参阅我在下面添加的答案。
编辑:工作代码现在看起来像:
//In the constructor...
DisplayMetrics dm = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
mTargetScreenXRatio = (float)(dm.widthPixels / 480);
mTargetScreenYRatio = (float)(dm.heightPixels / 320);
//Center of canvas
float centerX = canvas.getWidth() / 2;
float centerY = canvas.getHeight() / 2;
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mBackground.getWidth() / 2), -(mBackground.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX, centerY);
canvas.drawBitmap(mBackground, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mFlatBobble.getWidth() / 2), -(mFlatBobble.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX-(10 * mScale * mTargetScreenXRatio), centerY + (50 * mScale * mTargetScreenYRatio));
canvas.drawBitmap(mFlatBobble, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mBobble.getWidth() / 2), -(mBobble.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX + (68 * mScale * mTargetScreenXRatio), centerY + (78 * mScale * mTargetScreenYRatio));
canvas.drawBitmap(mBobble, mDrawingMatrix, null);
mDrawingMatrix.reset();
mDrawingMatrix.postTranslate(-(mMask.getWidth() / 2), -(mMask.getHeight() / 2));
mDrawingMatrix.postScale(mScale, mScale);
mDrawingMatrix.postTranslate(centerX, centerY);
canvas.drawBitmap(mMask, mDrawingMatrix, null);