2015-08-13 110 views
1

創建下圖後,我注意到由於某些原因,一些黑線顯得微弱,而其中一些清晰可見。可以使用哪些代碼來確保灰色框之間的黑線寬度恰好爲1dp,紅色矩形的寬度恰好爲5dp?畫布上暈乎乎的線條

enter image description here

public class RectangleTextView extends View { 
    private final Paint mBackPaint = new Paint(); 
    private final Paint mRedPaint = new Paint(); 
    private int mSideRectWidth = 10; 

    public RectangleTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     mBackPaint.setColor(Color.BLACK); 
     mRedPaint.setColor(Color.RED); 
    } 

    @Override protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     if (getWidth() == 0) 
      return; 

     //draw grey boxes 
     setBackgroundColor(Color.parseColor("#808080")); 
     int boxWidth = getWidth()/7; 

     //draw black line 
     for (int i = 0; i < 7; i++) { 
      canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint); 
     } 

     //draw left end rectangle 
     canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint); 

     //draw right end rectangle 
     canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint); 
    } 
} 
+0

'...確保灰色框之間的黑線寬度恰好爲1dp,紅色矩形的寬度恰好爲5dp?'也許你對** px **和* * DP **。畫布對象的'drawXYZ()'方法在** px **中工作,而您需要** dp **來爲密度獨立。 –

+0

因此,根據您當前的密度,您應該將所需的** dp ** s轉換爲** px ** s,以便讓'drawXYZ()'方法使用正確的值。 –

+0

'mBackPaint.setStrokeWidth(2f);' –

回答

1

是整個方式,你初始化Paint對象?我不知道默認構造函數使用的默認值。我通常明確地設置它們:取下ANTI_ALIAS_FLAG,將樣式設置爲Paint.Style.STROKE並設置所需的筆劃width。您需要的某些值可能是默認值,我只是不知道。

在處理細線時,關閉ANTI_ALIAS_FLAG可能非常重要。

+0

需要查看一些代碼,因爲我從來沒有這樣做過。我希望細線精確到1dp。 – MacaronLover

+0

int valueInPx =(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,,getResources()。getDisplayMetrics()); 或 int valueInPx = getResources()。getDimension(resourceID) - 用於從資源中讀取 \t \t Paint linePaint = new Paint(); \t \t linePaint.setAntiAlias(false); \t \t linePaint.setStrokeWidth(valueInPx); \t \t linePaint.setStyle(Style.STROKE); –