Android 在画布上绘制对象/图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2172523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:49:13  来源:igfitidea点击:

draw object/image on canvas

androidgoogle-mapsbitmap

提问by lulala

Is there another way to draw an object on a canvas in android?

有没有另一种方法可以在android的画布上绘制对象?

This code inside draw() doesn't work:

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

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

Well actually, it's working on my 1st code but when I've transfered this to another class called MarkOverlay, it's not working anymore.

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

  markerOverlay = new MarkerOverlay(getApplicationContext(), p);
                      listOfOverlays.add(markerOverlay);  

What parameter should I pass to MarkerOverlay to make this code work? The error is somewhere in getResources().

我应该向 MarkerOverlay 传递什么参数才能使此代码工作?错误在 getResources() 中的某个地方。

FYI, canvas.drawOval is perfectly working but I really want to draw an Image not an Oval. :)

仅供参考,canvas.drawOval 工作正常,但我真的想绘制一个图像而不是椭圆形。:)

回答by Nivish Mittal

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

回答by Emlyn

I prefer to do this as it only generates the image once:

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

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