android 画布上的可绘制图像

hec6srdp  于 2023-05-05  发布在  Android
关注(0)|答案(7)|浏览(187)

我怎样才能得到一个图像到画布上,以便在该图像上绘制?

0pizxfdo

0pizxfdo1#

在画布上绘制Drawable的好方法不是自己解码,而是让系统来解码:

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

这将适用于所有类型的可绘制对象,而不仅仅是位图。这也意味着你可以重复使用相同的绘图,如果只是大小的变化。

rqcrx0a6

rqcrx0a62#

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

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

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

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

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

iibxawm4

iibxawm43#

你也可以用这种方式。它会改变你大drawble适合你的画布:

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

6jygbczu4#

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

pinkon5k5#

试试这个

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

        }
6uxekuva

6uxekuva6#

为了保持我的矢量绘图的长宽比,我这样做了(在

Kotlin中):

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

vdzxcuhz7#

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

    }

}

相关问题