自定义视图Canvas onDraw()不会绘制任何内容 [英] Custom view Canvas onDraw() doesnt draw anything
问题描述
我正在尝试使用画布绘制一个椭圆形,但是它从未被绘制过.
这是我的自定义视图代码.我还用过setWillNotDraw(false)
仍然没有任何东西画在屏幕上.
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.
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);
}
}
有什么建议吗?
推荐答案
问题是getWidth()和getHeight()是O.将其更改为您的要求.
The problem is getWidth() and getHeight() is O. Change that to your requirement.
您可以使用以下内容作为参考.
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);
}
}
}
根据需要更改坐标和颜色.上面绘制了一个圆,但是您可以更改坐标以绘制椭圆,例如canvas.drawOval(new RectF(50,50,20,40),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 onDraw()不会绘制任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!