2014-12-07 115 views
0

我正在开发一个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); 


} 

回答

1

Bitmap.setWidthBitmap.setHeight是从API19(KitKat)引入的。

你没有将minSdkVersion设置为19或更高?

更新:

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

yes my minsdkvertion is 19 – 2014-12-07 16:41:30

+0

@ user3768819 ok,那么您是否将'BitmapFactory.Options()。inMutable = true'作为'BitmapFactory.decodeResource'方法的第三个参数? – hata 2014-12-07 16:58:07

2

既然你只缩放原始位图,你可能想使用folllowing方法

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(...)会一直被调用,并且总是重新创建相同的位图会很慢且浪费。

0

如果要加载位图资源的缩小版本到内存中传递正确设置BitmapFactory.OptionsdecodeResource方法。 Load a Scaled Down Version into Memory如果要缩放内存中已有的位图,请使用Bitmap#createScaledBitmap