创建下图后,我注意到由于某些原因,一些黑线显得微弱,而其中一些清晰可见。可以使用哪些代码来确保灰色框之间的黑线宽度恰好为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);' –