画布上的可绘图像

我如何才能得到一个图像的画布,以绘制在该图像?

188913 次浏览

try this

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


}

You need to load your image as bitmap:

 Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);

Then make the bitmap mutable and create a canvas over it:

Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));

You then can draw on the 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);


}


}

The good way to draw a Drawable on a canvas is not decoding it yourself but leaving it to the system to do so:

Drawable d = getResources().getDrawable(R.drawable.foobar, null);
d.setBounds(left, top, right, bottom);
d.draw(canvas);

This will work with all kinds of drawables, not only bitmaps. And it also means that you can re-use that same drawable again if only the size changes.

also you can use this way. it will change your big drawble fit to your canvas:

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

To preserve the aspect ratio of my vector drawable I did this:

val drawable = resources.getDrawable(R.drawable.my_vector, null)
val aspectRatio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight
val desiredWidthInPx = 100
val derivedHeightInPx = (desiredWidthInPx / aspectRatio).toInt()
drawable.setBounds(0, 0, desiredWidthInPx, derivedHeightInPx)
drawable.draw(canvas)