【发布时间】:2014-06-12 17:51:12
【问题描述】:
到目前为止,我已经尝试了许多将图像缩放到屏幕尺寸的方法,但它们似乎都不适合我。我对 java 还是很陌生,拥有适合任何屏幕尺寸的 UI 的想法对我来说似乎很陌生。我正在用 Canvas 类绘制位图。我试过创建一个 scaledBitmap 并没有看到任何区别。我想要一个像这样的简单主菜单屏幕
这一定是一个非常普遍的问题,因为所有应用都需要这样做。我真的可以使用一些帮助来理解它是如何工作的。在某些手机上看起来不错,但在其他手机上图像太大或偏离中心。
我的代码如下。如果有人可以在这里帮助我,这是一个即将到期的学校项目:P 谢谢大家!
public MainMenu(Context context) {
super(context);
titleBounds = new RectF();
playBounds = new RectF();
scoreBounds = new RectF();
soundBounds = new RectF();
creditBounds = new RectF();
titlePaint = new Paint();
playPaint = new Paint();
play = BitmapFactory.decodeResource(getResources(), R.drawable.play);
playGlow = BitmapFactory.decodeResource(getResources(), R.drawable.playglow);
sound = BitmapFactory.decodeResource(getResources(), R.drawable.sound);
soundGlow = BitmapFactory.decodeResource(getResources(), R.drawable.soundglow);
// Get window size and save it to screenWidth and screenHeight.
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
playy = Bitmap.createScaledBitmap(play, convertToPx(screenWidth), convertToPx(screenHeight), true);
playSound(context, R.raw.loop);
}
public int convertToPx(int dp) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (dp * scale + 0.5f);
}
@Override protected void onDraw(Canvas canvas) {
ViewGroup parent = (ViewGroup)getParent();
playBounds.set(screenWidth / 2 - play.getWidth() / 2, screenHeight * 1/3 - play.getHeight() / 2, playBounds.left + play.getWidth(), playBounds.top + play.getHeight());
soundBounds.set(playBounds.centerX() - sound.getWidth() / 2, playBounds.bottom + 10, soundBounds.left + sound.getWidth(), soundBounds.top + sound.getHeight());
if (playClick == false) canvas.drawBitmap(playy, null, playBounds, null);
else canvas.drawBitmap(playGlow, null, playBounds, null);
if (soundClick == false) canvas.drawBitmap(sound, null, soundBounds, null);
else canvas.drawBitmap(soundGlow, null, soundBounds, null);
【问题讨论】:
标签: java android canvas bitmap scaling