我想像所附图像一样绘制图表,但我无法在右侧绘制红色垂直矩形以及将其他对象放在顶部。最大的担忧是与众多不同屏幕尺寸的 Android 设备有关。我完全理解我在此过程中想要实现的目标,其中包括以下目标。所有帮助将不胜感激。
- 屏幕两边各有 1 个红色矩形(右手边我不知道怎么画)
- 红色垂直矩形之间的 7 个灰色框需要宽度相等
- 黑色垂直线需要在矩形之间,就像上图一样
- 显示数字的文本框需要位于每个灰色矩形的中心以及红色的小矩形
- 我还希望将来能够重用该图表,以便我可以随时用红色或黑色填充小盒子
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<my.package.name.ComplexDiagram
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_centerVertical="true"
/>
</RelativeLayout>
爪哇
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class ComplexDiagram extends View {
private int measuredWidth, measuredHeight;
private Paint mGreyRectPaint, mBlackLinePaint, mRedRectPaint;
private RectF mGreyRect, mBlackLineF, mRedRectF;
public ComplexDiagram(Context context) {
super(context);
init(context, null, 0);
}
public ComplexDiagram(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public ComplexDiagram(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attributeSet, int defStyle) {
mGreyRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mGreyRectPaint.setColor(0xFF3C3C3C);
mGreyRectPaint.setStyle(Paint.Style.FILL);
mBlackLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBlackLinePaint.setColor(0xFF000000);
mBlackLinePaint.setStyle(Paint.Style.FILL);
mRedRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRedRectPaint.setColor(0xFFCC3333);
mRedRectPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (measuredHeight == 0 || measuredWidth == 0)
return;
canvas.drawRect(mGreyRect, mGreyRectPaint);
canvas.drawRect(mBlackLineF, mBlackLinePaint);
canvas.drawRect(mRedRectF, mRedRectPaint);
}
}