How can I get the canvas size of a custom view outside of the onDraw method?

后端 未结 1 891
耶瑟儿~
耶瑟儿~ 2020-12-30 19:50

I need to be able to access the size of the view\'s canvas to perform some calculations. For some reason, the size of the view passed to onSizeChanged is differ

相关标签:
1条回答
  • 2020-12-30 20:56

    For drawing purposes, you should not really use the dimensions of the Canvas object.

    Just use the dimensions provided to you in the onSizeChanged method. You can either store the dimensions for use in the onDraw method or resize/draw to a backing bitmap that you can draw with later.

    Update:

    Quickly whipped up some code, it looks like this works:

    public class CustomView extends View{
        private Paint paint;
        private int w;
        private int h;
    
        public CustomView(Context context, AttributeSet attr) {
            super(context, attr);
            paint = new Paint();
            paint.setTextAlign(Align.CENTER);
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            this.w = w;
            this.h = h;
            super.onSizeChanged(w, h, oldw, oldh);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);
            canvas.drawText("TEST", w/2, h/2, paint);   
        }
    }
    

    Update 2

    Following the circle code update.

    We can do this:

       @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);
            float centerX = (float) w/2;
            float centerY = (float) h/2;
            float radianAngle = (float) Math.toRadians(startAngle);
    
            radius[0] = centerX;
            radius[1] = centerY;
            radius[2] = centerX + centerX * FloatMath.cos(radianAngle);
            radius[3] = centerY + centerY * FloatMath.sin(radianAngle);
    
            paint.setColor(0xFF330000);
            paint.setStrokeWidth(1);
            canvas.drawLines(radius, paint);
        }
    

    You'll see that this now works on any sized view.

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