我一直在尝试在画布上绘制折线。我的代码中没有错误,但是未显示所连接的线段顺序。请在下面找到代码段;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
public class MyView extends View {
private Paint redPaint;
public MyView(Context context) {
super(context, null);
redPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
redPaint.setStyle(Paint.Style.STROKE);
redPaint.setColor(0xffff0000);
redPaint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(10,30,200,200,redPaint);
canvas.drawCircle(300,300,250,redPaint);
Path mylines=new Path();
mylines.moveTo(0,0);
mylines.lineTo(1,1);
mylines.lineTo(2,2);
mylines.lineTo(3,3);
mylines.lineTo(4,4);
Paint GreenPaint=new Paint();
GreenPaint.setARGB(255,0,255,0);
canvas.drawPath(mylines,GreenPaint);
}
}
您的代码在很大程度上是正确的。您没有像GreenPaint
那样完全初始化redPaint
,这是一个问题。第二个问题虽然可能不是问题,但它的折线形状太小,即使使用完全初始化的GreenPaint
,您也可能会错过它。
这里是自定义视图的更新版本,带有附加的构造函数和初始化的greenPaint
。我还更改了折线的形状,使其变大以便于查看-这只是代码中的斑点。另外,我将对象分配移出了onDraw()
。
public class MyView extends View {
Path mylines = new Path();
private Paint redPaint;
private Paint greenPaint;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context) {
super(context, null);
init();
}
private void init() {
redPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
redPaint.setStyle(Paint.Style.STROKE);
redPaint.setColor(0xffff0000);
redPaint.setStrokeWidth(5);
greenPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
greenPaint.setStyle(Paint.Style.STROKE);
greenPaint.setARGB(255, 0, 255, 0);
greenPaint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(10, 30, 200, 200, redPaint);
canvas.drawCircle(300, 300, 250, redPaint);
mylines.moveTo(0, 0);
mylines.lineTo(200, 50);
mylines.lineTo(300, 150);
mylines.lineTo(400, 250);
mylines.lineTo(500, 300);
canvas.drawPath(mylines, greenPaint);
}
}
这里是显示器。 (我为该视图的可见性添加了灰色背景,但这不是必需的。)