Canvas does not draw in Custom View

对着背影说爱祢 提交于 2019-11-30 22:49:49

问题


I created a Custom View CircleView like this:

public class CircleView extends LinearLayout {

    Paint paint1;
    public CircleView(Context context) {
        super(context);
        init();
    }   
    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public void init() {
        paint1 = new Paint();
        paint1.setColor(Color.RED); 
    }       
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);         
        canvas.drawCircle(50, 50, 25, paint1);
        this.draw(canvas);  
    }
}

Then I included it on my Activity's layout root <RelativeLayout>:

  <com.turkidroid.test.CircleView
      android:id="@+id/circle_view"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" 
      android:layout_centerInParent="true"  />  

However, nothing was drawn!

  • Am I implementing the Custom View right?
  • Or is it how I used the Custom View?

Some Info:

  • Both CircleView and MyActivity are in the same package: com.turkidroid.test.
  • In onDraw() method, I tried including super.onDraw() and commenting it.
  • I know I can draw a circle with much simpler approaches but my CircleView will contain more than drawing a circle. I need to make it a Custom View.

回答1:


Your onDraw method is never called, you need to call setWillNotDraw(false) on the constructor of your Custom View in order to get onDraw actually called.

As stated on Android SDK:

If this view doesn't do any drawing on its own, set this flag to allow further optimizations. By default, this flag is not set on View, but could be set on some View subclasses such as ViewGroup. Typically, if you override onDraw(android.graphics.Canvas) you should clear this flag.




回答2:


Where is your this.draw() method?

This should work definitively:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);         
    canvas.drawCircle(50, 50, 25, paint1);
    //this.draw(canvas);  where is this method?
}


来源:https://stackoverflow.com/questions/12261435/canvas-does-not-draw-in-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!