画布上的可绘制图像

时间:2011-03-03 03:49:11

标签: android

如何在画布上绘制图像以便在该图像上绘图?

7 个答案:

答案 0 :(得分:149)

在画布上绘制Drawable的好方法不是自己解码,而是将其留给系统来执行此操作:

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

这适用于所有类型的drawable,而不仅仅是位图。而且这也意味着如果尺寸发生变化,你可以再次使用相同的drawable。

答案 1 :(得分:36)

您需要将图片加载为位图:

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

然后使位图变为可变并在其上创建一个画布:

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

然后你可以在画布上画画。

答案 2 :(得分:13)

你也可以用这种方式。它会改变你画布的大抽奖:

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);

答案 3 :(得分:8)

试试这个

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

        }

答案 4 :(得分:8)

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

答案 5 :(得分:1)

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

    }

}

答案 6 :(得分:0)

为了保持我的矢量可绘制对象的纵横比,我这样做了:

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)