2012-07-10 59 views
1

我有一個封閉的路徑,我想用一種顏色(白色)填充它,並在其周圍放置另一種顏色(紅色)的邊緣。我想到了一個自定義視圖類,可以讓我達到這個目的:DrawPath在android自定義視圖

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是我定義的路徑在活動中。這是有效的,因爲我可以在使用它定義PathShape時繪製它。 但在這種情況下,Eclipse給我錯誤java.lang.NullPointerException。我試圖在XML佈局中定義自定義視圖,但這也不起作用。在android中使用形狀一直非常令人沮喪,所以如果有人能夠提供幫助,這將非常棒!

回答

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); 
    } 
} 
+0

我使用你的代碼,現在它工作正常。謝謝! – tangfucius 2012-07-10 17:12:03

0

strokePaint永遠不會在您的代碼中初始化......是您的nullPointer?

歡迎使用堆棧...如果您發現有用的答案upvote他們......如果您認爲他們是正確的,給他們一個綠色的選中標記!

+0

這也正是它。很多小細節要注意......謝謝! – tangfucius 2012-07-10 17:11:15

+0

真棒!給我一個綠色的複選標記! – 2012-07-10 17:34:24