在画布上绘制对象/图像

lul*_*ala 20 android google-maps bitmap

还有另一种在android中的画布上绘制对象的方法吗?

draw()中的这段代码不起作用:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
Run Code Online (Sandbox Code Playgroud)

实际上,它正在处理我的第一个代码,但是当我将它转移到另一个名为MarkOverlay的类时,它就不再起作用了.

  markerOverlay = new MarkerOverlay(getApplicationContext(), p);
                      listOfOverlays.add(markerOverlay);  
Run Code Online (Sandbox Code Playgroud)

我应该将哪个参数传递给MarkerOverlay以使此代码有效?错误发生在getResources()中.

仅供参考,canvas.drawOval是完美的工作,但我真的想画一个图像而不是椭圆形.:)

小智 23

package com.canvas;

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.View;

public class Keypaint extends View {
    Paint p;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        p=new Paint();
        Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        p.setColor(Color.RED);
        canvas.drawBitmap(b, 0, 0, p);
    }

    public Keypaint(Context context) {
        super(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不要在onDraw中解码图像 - 在渲染循环外执行尽可能多的繁重操作. (11认同)
  • 您必须使用Bitmap.recycle()释放位图数据,否则您会遇到令人讨厌的内存泄漏:在每个绘图周期中创建一个新的位图. (8认同)

小智 19

我更喜欢这样做,因为它只生成一次图像:

public class CustomView extends View {

    private Drawable mCustomImage;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCustomImage = context.getResources().getDrawable(R.drawable.my_image);
    }

    ...

    protected void onDraw(Canvas canvas) {
        Rect imageBounds = canvas.getClipBounds();  // Adjust this for where you want it

        mCustomImage.setBounds(imageBounds);
        mCustomImage.draw(canvas);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1表示不在onDraw中进行分配或解压缩图像 (6认同)