在canvas上绘制图像
如何在canvas上获取图像以便在该图像上绘制?
在canvas上绘制Drawable的好方法不是自己解码,而是将其留给系统来完成:
Drawable d = getResources().getDrawable(R.drawable.foobar); d.setBounds(left, top, right, bottom); d.draw(canvas);
这将与各种绘图工作,不仅位图。 而且这也意味着只要尺寸发生变化就可以再次使用同样的drawable。
您需要将图像加载为位图:
Resources res = getResources(); Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);
然后使位图可变,并创build一个canvas:
Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));
然后你可以在canvas上画画。
也可以使用这种方式。 它会改变你的canvas的适合你的canvas:
Resources res = getResources(); Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable); yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);
尝试这个
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); }
Drawable d = ContextCompat.getDrawable(context, R.drawable.***) d.setBounds(left, top, right, bottom); d.draw(canvas);
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); } }
我不确定是否必须将图像作为位图加载( http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android /widget/ProgressBar.java#ProgressBar.onDraw%28android.graphics.Canvas%29 )使用Drawable.draw(Canvas c)
。