[英]Custom view Canvas onDraw() doesnt draw anything
I am trying to draw a oval using canvas, but it never gets drawn.我试图用画布画一个椭圆,但它永远不会被画出来。 Here is my code for the custom view.这是我的自定义视图代码。 I have also used setWillNotDraw(false)
still nothing gets drawn on the screen.我也使用过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);
}
}
Any suggestions?有什么建议么?
when called in init(): rect = new RectF(0.1f, 0.1f, getWidth(),getHeight());在 init() 中调用时: rect = new RectF(0.1f, 0.1f, getWidth(),getHeight());
both getWidth() & getHeight() return 0 getWidth() 和 getHeight() 都返回 0
The problem is getWidth() and getHeight() is O. Change that to your requirement.问题是 getWidth() 和 getHeight() 是 O。将其更改为您的要求。
You can use the below as a reference.您可以使用以下内容作为参考。
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);
}
}
}
Change the co-ordinates and color to your requirements.根据您的要求更改坐标和颜色。 The above draws a circle but you can change the co-ordinates to draw oval something like canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);上面绘制了一个圆,但您可以更改坐标以绘制椭圆形,例如 canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.