創建下圖後,我注意到由於某些原因,一些黑線顯得微弱,而其中一些清晰可見。可以使用哪些代碼來確保灰色框之間的黑線寬度恰好爲1dp,紅色矩形的寬度恰好爲5dp?畫布上暈乎乎的線條
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);
}
}
'...確保灰色框之間的黑線寬度恰好爲1dp,紅色矩形的寬度恰好爲5dp?'也許你對** px **和* * DP **。畫布對象的'drawXYZ()'方法在** px **中工作,而您需要** dp **來爲密度獨立。 –
因此,根據您當前的密度,您應該將所需的** dp ** s轉換爲** px ** s,以便讓'drawXYZ()'方法使用正確的值。 –
'mBackPaint.setStrokeWidth(2f);' –