如何覆盖onDraw,以获取将要绘制的内容(作为位图)并进行转换? [英] How can I override onDraw so that I take what would have been drawn (as a bitmap) and transform it?

查看:101
本文介绍了如何覆盖onDraw,以获取将要绘制的内容(作为位图)并进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的方法有效,但不幸的是,该方法涉及到创建整个屏幕大小的位图-而不仅仅是绘制区域.如果我使用它来绘制UI元素,则会为每个UI元素重新绘制 .这样可以更有效吗?

The method below works, but it unfortunately, this method involves creating a bitmap the size of the entire screen - not just the area that is drawn to. If I use this to draw UI elements, it is redrawn for each UI element. Can this be done more efficiently?

@Override
protected void onDraw(Canvas canvas) {
    //TODO: Reduce the burden from multiple drawing
    Bitmap bitmap=Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.ARGB_8888);
    Canvas offscreen=new Canvas(bitmap);
    super.onDraw(offscreen);
    //Then draw onscreen
    Paint p=new Paint();
    p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
    canvas.drawBitmap(bitmap, 0, 0, p);
}

推荐答案

以下代码将更加高效.

public class MyView extends TextView{
    private Canvas offscreen;

    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public MyView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //We want the superclass to draw directly to the offscreen canvas so that we don't get an infinitely deep recursive call
        if(canvas==offscreen){
            super.onDraw(offscreen);
        }
        else{
            //Our offscreen image uses the dimensions of the view rather than the canvas
            Bitmap bitmap=Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
            offscreen=new Canvas(bitmap);
            super.draw(offscreen);
            //Create paint to draw effect
            Paint p=new Paint();
            p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));
            //Draw on the canvas. Fortunately, this class uses relative coordinates so that we don't have to worry about where this View is actually positioned.
            canvas.drawBitmap(bitmap, 0, 0, p);
        }
    }
}

这篇关于如何覆盖onDraw,以获取将要绘制的内容(作为位图)并进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆