Answers:
在画布上绘制Drawable的好方法不是自己对其进行解码,而是将其留给系统来进行:
Drawable d = getResources().getDrawable(R.drawable.foobar, null);
d.setBounds(left, top, right, bottom);
d.draw(canvas);
这将适用于所有类型的可绘制对象,而不仅仅是位图。而且这还意味着,只要更改大小,您就可以再次使用同一可绘制对象。
您需要将图像加载为位图:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);
然后使位图可变,并在其上创建画布:
Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));
然后,您可以在画布上绘制。
您也可以使用这种方式。它将改变您的大画布在画布上的尺寸:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);
Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);
试试这个
Bitmap mBitmap = Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
}
package com.android.jigsawtest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurafaceClass extends SurfaceView implements
SurfaceHolder.Callback {
Bitmap mBitmap;
Paint paint =new Paint();
public SurafaceClass(Context context) {
super(context);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
// TODO Auto-generated constructor stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mBitmap, 0, 0, paint);
}
}