How can I override onDraw so that I take what would have been drawn (as a bitmap) and transform it?

后端 未结 3 1375
再見小時候
再見小時候 2020-12-16 04:59

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 dra

3条回答
  •  执笔经年
    2020-12-16 05:38

    The following code will be much more efficient.

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

提交回复
热议问题