【问题标题】:draw object/image on canvas在画布上绘制对象/图像
【发布时间】:2011-01-11 11:11:15
【问题描述】:

还有其他方法可以在 android 的画布上绘制对象吗?

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

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

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

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

我应该将什么参数传递给 MarkerOverlay 以使此代码正常工作?错误出现在 getResources() 中。

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

【问题讨论】:

    标签: android google-maps bitmap


    【解决方案1】:

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

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

    【讨论】:

    • +1 表示不在 onDraw 中进行分配或解包图像
    • 给了我这个日食警告:在绘制操作期间避免对象分配:使用 Canvas.getClipBounds(Rect) 而不是分配临时 Rect 的 Canvas.getClipBounds()
    • 如果您遵循 Eclipse 提供的简单优化器命中,这可以做得更好。 IE。 canvas.getClipBounds(imageBounds); mCustomImage.setBounds(imageBounds);拥有超快的 onDraw 非常重要。
    • getResources().getDrawable() 自 API 22 起已弃用。请改用 ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);。
    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

    • 您必须使用 Bitmap.recycle() 释放位图数据,否则会导致严重的内存泄漏:在每个绘图周期中创建一个新位图。
    • 不要在 onDraw 中解码图像 - 在渲染循环之外做尽可能多的繁重工作。
    • 是否可以在画布上设置视频视图?
    猜你喜欢
    • 2018-06-02
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 2013-07-20
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多