Java - 使位图缩放到您的屏幕大小?

时间:2014-06-11 21:07:54

标签: java android bitmap scale

我正在创建一个应用程序,并希望我的ui可以随手机扩展。我正在将位图导入画布并按如下方式绘制它们:

public class MainMenu extends View {

private RectF titleBounds, playBounds, scoreBounds, soundBounds, creditBounds;
private Paint titlePaint, playPaint;

private boolean playClick = false, startPlay = false, scoreClick = false, startScore = false, soundClick = false, startSound = false, creditsClick = false, startCredits = false;


public Bitmap play;
public Bitmap playGlow;

public Bitmap sound;
public Bitmap soundGlow;


public int screenWidth, screenHeight;

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;
}


@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(scoreBounds.centerX() - sound.getWidth() / 2, scoreBounds.bottom + 10, soundBounds.left + sound.getWidth(), soundBounds.top + sound.getHeight());

问题是没有什么可以缩放图像以适应手机,它只是读取我导入的图像的x和y大小。有什么方法可以缩放图像?

1 个答案:

答案 0 :(得分:0)

使用Bitmap类的createScaledBitmap

bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);

它会缩放您的位图,但不会超过宽度和高度,因为它会导致您的位图模糊。

<强>文件:

    Creates a new bitmap, scaled from an existing bitmap, when possible. 
   If the specified width and height are the same as the current width and height of the source bitmap,
   the source bitmap is returned and no new bitmap is created.

全屏

bitmap  = Bitmap.createScaledBitmap(bitmap, screenWidth , screenHeight , true);