我正在尝试使用canvas绘制椭圆。但它永远不会被绘制。 这是我的自定义view.i的代码也使用了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.1f, 0.1f, getWidth(), getHeight());
paint =new Paint();
paint.setShader(new LinearGradient(0.40f, 0.0f, 100.60f, 100.0f,
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);
}
}
任何建议??
答案 0 :(得分:2)
在init()中调用时:rect = new RectF(0.1f,0.1f,getWidth(),getHeight());
getWidth()& getHeight()返回0
答案 1 :(得分: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那样的椭圆形(新的RectF(50,50,20,40),mPaint);