1

我有一个封闭的路径,我想用一种颜色(白色)填充它,并在它周围放置另一种颜色(红色)的边缘。我认为自定义视图类可以让我达到这个目的:

public class StrokeFill extends View{
private Path shapePath;
private Paint strokePaint;
private Paint fillPaint;


public StrokeFill(Context context, Path path) {
    super(context);
    shapePath = path;
    fillPaint.setColor(android.graphics.Color.WHITE);
    fillPaint.setStyle(Paint.Style.FILL);
    fillPaint.setStrokeWidth(0);
    strokePaint.setColor(android.graphics.Color.RED);
    strokePaint.setStyle(Paint.Style.STROKE);
    strokePaint.setStrokeWidth(3);
    // TODO Auto-generated constructor stub
}

protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    //canvas.drawColor(Color.BLACK);
    super.onDraw(canvas);
    canvas.drawPath(shapePath, fillPaint);
    canvas.drawPath(shapePath, strokePaint);
}
}

在我的主要活动中,我只是这样做了(没有 XML 布局文件):

setContentView(new StrokeFill(this, testpath));

testpath 是我在Activity中定义的路径。这是有效的,因为当我使用它定义 PathShape 时,我能够绘制它。但在这种情况下,Eclipse 给了我错误 java.lang.NullPointerException。我尝试在 XML 布局中定义自定义视图,但这也不起作用。到目前为止,在 android 中使用形状非常令人沮丧,所以如果有人能提供帮助,那就太好了!

4

2 回答 2

1

你的初始化问题看看这个

public class StrokeFill extends View{
    private Path shapePath;
    private Paint strokePaint;
    private Paint fillPaint;

    public StrokeFill(Context context, Path path) {
       super(context);
       shapePath = new Path();        
       shapePath = path;
       fillPaint = new Paint();
       fillPaint.setColor(android.graphics.Color.WHITE);
       fillPaint.setStyle(Paint.Style.FILL);
       fillPaint.setStrokeWidth(0);
       strokePaint = new Paint();
       strokePaint.setColor(android.graphics.Color.RED);
       strokePaint.setStyle(Paint.Style.STROKE);
       strokePaint.setStrokeWidth(3);
       // TODO Auto-generated constructor stub
    }

   protected void onDraw(Canvas canvas) {
      // TODO Auto-generated method stub
      //canvas.drawColor(Color.BLACK);
      super.onDraw(canvas);
      canvas.drawPath(shapePath, fillPaint);
      canvas.drawPath(shapePath, strokePaint);
  }
}
于 2012-07-10T17:03:33.383 回答
0

strokePaint 从未在您的代码中初始化......那是您的 nullPointer 吗?

欢迎加入堆栈...如果您发现有用的答案,请点赞...如果您认为它们是正确的,请给他们绿色的复选标记!

于 2012-07-10T16:44:47.773 回答