【问题标题】:DrawPath in android Custom Viewandroid自定义视图中的DrawPath
【发布时间】:2012-07-10 16:42:32
【问题描述】:

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

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 中使用形状非常令人沮丧,所以如果有人能提供帮助,那就太好了!

【问题讨论】:

    标签: android canvas


    【解决方案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);
      }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 就是这样。这么多小细节要注意...谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多