在Android中添加BitMap资源以绘制对象

时间:2016-02-08 23:17:21

标签: android bitmap android-canvas paint android-bitmap

我有一个Pain Object,我想从Android资源覆盖一个Bitmap。

{{1}}

这可能很简单。我不了解Android绘图,画布和位图关系。

1 个答案:

答案 0 :(得分:0)

Paint对象用于在View的“onDraw”方法中设置canvas操作的样式。该canvas对象允许您直接向其绘制位图。因此,如果您希望将位图作为背景,则可以先绘制位图,然后使用其他画布操作在顶部使用已配置的Paint对象进行绘制,以设置这些绘制操作的样式。

请参阅View#onDraw()以及API文档中链接的Canvas对象: http://developer.android.com/reference/android/view/View.html#onDraw(android.graphics.Canvas)

其他提示,避免在onDraw方法中分配对象。创建您的Paint对象并在其他位置加载您的位图,并保留对它们的引用,以便在onDraw方法中使用。

非常简单的例子:

public class CustomView extends View {

    private Bitmap background;
    private Paint paint;
    private float size;

    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {

        // Prepare your paint objects
        paint = new Paint();
        paint.setStrokeWidth(2);
        paint.setColor(Color.RED);

        // Load your bitmap
        background = BitmapFactory.decodeResource(getResources(), R.drawable.waracle_square);

        // Calculate density dependant variables
        size = getResources().getDisplayMetrics().density * 100;

    }

    @Override
    protected void onDraw(Canvas canvas) {

        // The paint is optional when drawing an image
        canvas.drawBitmap(background, 0, 0, null);

        // red circle of size 100dp in top left corner
        canvas.drawOval(0, 0, size, size, paint);

    }


}