1

我正在尝试使用画布绘制一个椭圆,但它永远不会被绘制。这是我的自定义视图代码。我也用过setWillNotDraw(false),屏幕上仍然没有绘制任何内容。

public class Myview extends View {
    Paint paint;
    RectF rect;
    public Myview(Context context) {
        super(context);
        init();
        setWillNotDraw(false);
    }

    public Myview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        setWillNotDraw(false);
    }

    public Myview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
        setWillNotDraw(false);
    }

    private void init() {
        rect = new RectF(0.1 f, 0.1 f, getWidth(), getHeight());
        paint = new Paint();
        paint.setShader(new LinearGradient(0.40 f, 0.0 f, 100.60 f, 100.0 f,
            Color.parseColor("#ffffff"),
            Color.parseColor("#Ffffff"),
            Shader.TileMode.CLAMP));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        setMeasuredDimension(200, 200);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawOval(rect, paint);
    }
}

有什么建议么?

4

2 回答 2

2

在 init() 中调用时: rect = new RectF(0.1f, 0.1f, getWidth(),getHeight());

getWidth() 和 getHeight() 都返回 0

于 2013-05-17T09:24:59.903 回答
2

问题是 getWidth() 和 getHeight() 是 O。将其更改为您的要求。

您可以使用以下内容作为参考。

public class MainActivity extends Activity
{    

MyView mv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mv= new MyView(this);
setContentView(mv);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
mPaint.setShader(new LinearGradient(0.40f, 0.0f, 100.60f, 100.0f, 
      Color.RED,
      Color.RED,
      Shader.TileMode.CLAMP));

}

private Paint       mPaint;

public class MyView extends View{
  Paint paint;
  RectF rect;
   public MyView(Context context) {
          super(context);
          rect = new RectF(20, 20, 100,100);
          //canvas.drawOval(new RectF(50, 50, 20, 40), p)
   }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

      setMeasuredDimension(200, 200);

  }



  @Override
      protected void onDraw(Canvas canvas) {
          super.onDraw(canvas);
          canvas.drawOval(rect, mPaint);

      }
  }
}

根据您的要求更改坐标和颜色。上面画了一个圆圈,但您可以更改坐标以绘制椭圆,例如 canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);

在此处输入图像描述

于 2013-05-17T09:50:51.440 回答