我在 activity_main.xml 中放置了一个从 View 扩展的类,我想在它周围画一个边界。所以我将坐标存储在一个数组中并调用线条绘制函数,如下所示:
private void initView(Context ctx) {
if(!initialized) {
initialized = true;
linePaint.setColor(Color.GREEN);
// linePaint.setStrokeWidth(2.0f);
}
}
@Override
public void onDraw(Canvas canvas) {
if(cachedBitmap == null) {
// cachedBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
cachedBitmap = Bitmap.createBitmap(getWidth(), 200, Config.ARGB_8888);
// cachedBitmap.setHasAlpha(false);
// cachedBitmap.eraseColor(Color.WHITE);
cachedCanvas = new Canvas(cachedBitmap);
}
COORDS[0][0] = 0.0f; // Left-Top
COORDS[0][1] = 0.0f;
COORDS[1][0] = 0.0f; // Left-Bottom
COORDS[1][2] = getHeight();
COORDS[2][0] = getWidth(); // Right-Bottom
COORDS[2][3] = getHeight();
Log.d("MYLOG", "(2,0)="+Float.toString(COORDS[2][0])+" "+"(2,1)="+Float.toString(COORDS[2][4]) );
COORDS[3][0] = getWidth(); // Right-Top
COORDS[3][5] = 0.0f;
///*
// drawLine(COORDS[0][0], COORDS[0][6], COORDS[1][0], COORDS[1][7], linePaint);
// drawLine(COORDS[0][0]+5.0f, COORDS[0][8]+5.0f, COORDS[1][0]+5.0f, COORDS[1][9]+5.0f, linePaint);
canvas.drawLine(COORDS[0][0], COORDS[0][10], COORDS[1][0], COORDS[1][11], linePaint);
cachedCanvas.drawLine(COORDS[0][0], COORDS[0][12], COORDS[1][0], COORDS[1][13], linePaint);
// */
/*
canvas.drawLine(0.0f, 0.0f, 100.0f, 0.0f, linePaint);
cachedCanvas.drawLine(0.0f, 0.0f, 100.0f, 100.0f, linePaint);
// */
canvas.drawLine(COORDS[1][0], COORDS[1][14], COORDS[2][0], COORDS[2][15], linePaint);
cachedCanvas.drawLine(COORDS[1][0], COORDS[1][16], COORDS[2][0], COORDS[2][17], linePaint);
canvas.drawLine(COORDS[2][0], COORDS[2][18], COORDS[3][0], COORDS[3][19], linePaint);
cachedCanvas.drawLine(COORDS[2][0], COORDS[2][20], COORDS[3][0], COORDS[3][21], linePaint);
canvas.drawLine(COORDS[3][0], COORDS[3][22], COORDS[0][0], COORDS[0][23], linePaint);
cachedCanvas.drawLine(COORDS[3][0], COORDS[3][24], COORDS[0][0], COORDS[0][25], linePaint);
canvas.drawBitmap(cachedBitmap, 0.0f, 0.0f, null); // Set position of bitmap within the canvas
}
这给了我以下输出
即使 getWidth() 和 getHeight() 返回正确的值。
无论如何,我想把行加粗一点,让输出看起来更清晰,所以我取消// linePaint.setStrokeWidth(2.0f);
了上面代码中的行的注释,但是现在输出看起来像这样:
- 为什么会这样?
- 如何更改线条的粗细?
- _编辑 - -
这是在activity_main中声明视图的方式:
<com.example.mybasicinteractivegraph.GraphBoarder
android:layout_width="100dp"
android:layout_height="100dp"
android:text="@string/hello_world" />
---编辑 2---
有android:layout_width = "wrap_content"