2010-01-31 144 views
18

有没有另一种方法在Android上的画布上绘制对象?在画布上绘制对象/图像

内得出这样的代码()不工作:

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是完美的工作,但我真的想画一个不是椭圆形的图像。 :)

回答

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

你必须释放与Bitmap.recycle()位图数据,否则你会得到一个讨厌的内存泄漏:在每个绘图周期中创建一个新的位图。 – 2013-03-31 07:16:03

+5

不要解码onDraw中的图像 - 在渲染循环外完成尽可能多的繁重工作。 – slott 2015-05-07 07:24:21

14

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

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

+1不进行分配或onDraw有 – user1532390 2013-02-15 15:22:32

+1

拆包的图像给了我这次日食警告:在抽吸操作避免对象分配:使用Canvas.getClipBounds(矩形),而不是Canvas.getClipBounds(),它分配一个临时矩形 – oat 2013-12-14 06:40:12

+1

这可能是如果您遵循Eclipse给出的简单优化器命中,则会更好。 IE浏览器。 \t \t canvas.getClipBounds(imageBounds); \t \t mCustomImage.setBounds(imageBounds); 拥有超快的onDraw非常重要。 – slott 2015-05-07 07:30:04