How to pass variables to custom View before onDraw() is called?

前端 未结 1 385
暖寄归人
暖寄归人 2021-01-17 04:54

What I am trying to achieve:

  • measure a container View in my layout, mainContainer, that is defined in the XML
  • pass the
相关标签:
1条回答
  • 2021-01-17 05:20

    What you need to do is add a flag inside your AvatarView that checks if are you going to render this or not in your onDraw method.

    sample:

       public class AvatarView extends ImageView {
    
        private Bitmap body;
        private Bitmap hat;
        private int containerHeight;
        private int containerWidth;
        private boolean isRender = false;
    
        public AvatarView(Context context) {
            super(context);
            init();
        }
    
        public AvatarView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public AvatarView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        public void setMeasure(int containerWidth, int containerHeight )
        {
            this.containerHeight = containerHeight;
            this.containerWidth = containerWidth;
        }
    
        private void init() {
            body = BitmapFactory.decodeResource(getResources(), R.drawable.battle_run_char);
            hat = BitmapFactory.decodeResource(getResources(), R.drawable.red_cartoon_hat);
        }
    
        public void setRender(boolean render)
        {
           isRender = render;
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if(isRender )
            {
                canvas.drawBitmap(body, x, y, null);
                canvas.drawBitmap(hat, x, y, null);
            }
    
        }
        }
    

    Now it wont render when you dont call setRender and set it to true. And just call setMeasure to pass the value.

    First you need to call setMeasure and after you set the measure you then call setRender(true) and call invalidate() to call the onDraw method to render the images

    0 讨论(0)
提交回复
热议问题