簡體   English   中英

調整位圖大小

[英]Resizing bitmap

我正在做一個android項目。 當我嘗試調整位圖的大小時,應用程序不幸停止並在Logcat中給出了一條消息“僅可變位圖可以調整大小”。 我試圖將位圖轉換為可變位仍然是同樣的問題。解決方案可能是什么。 我的代碼:

public DrawingTheBall(Context context) {
    super(context);

    ball= BitmapFactory.decodeResource(getResources(),R.drawable.start_bg);;

}

@Override
protected void onDraw( Canvas canvas) {
    super.onDraw(canvas);

     ball.setWidth(canvas.getWidth());
     ball.setHeight(canvas.getHeight());


    Paint p=new Paint();
    canvas.drawBitmap(ball,0,0,p);


}

由於僅縮放原始位圖,因此您可能需要使用以下方法

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

完整的代碼:

Bitmap newBmp = Bitmap.createScaledBitmap(ball, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(newBmp, 0, 0, p);

考慮將“ newBmp”行移至另一種方法,例如onSizeChanged(...) onDraw(...)幾乎onDraw(...)被調用,並且一直都在重新創建相同的位圖會很慢而且很浪費。

從API19(KitKat)引入了Bitmap.setWidthBitmap.setHeight

您沒有將minSdkVersion設置為19或更高版本嗎?

更新:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
ball= BitmapFactory.decodeResource(getResources(), R.drawable.start_bg, options);

如果要將位圖資源的按比例縮小版本加載到內存中,請通過將BitmapFactory.Options正確設置為decodeResource方法。 Bitmap#createScaledBitmap比例縮小的版本加載到內存中如果Bitmap#createScaledBitmap內存中已有的位圖,請使用Bitmap#createScaledBitmap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM