写一段Android 自定义柱状图代码
时间: 2023-11-27 10:55:26 浏览: 64
以下是一个简单的 Android 自定义柱状图的实现代码,使用 Canvas 和 Paint 绘制:
```java
public class BarChartView extends View {
private Paint mPaint;
private List<Integer> mData;
private int mMaxValue;
private int mBarWidth;
private int mBarColor;
public BarChartView(Context context) {
this(context, null);
}
public BarChartView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BarChartView);
mBarWidth = ta.getDimensionPixelSize(R.styleable.BarChartView_bar_width, 20);
mBarColor = ta.getColor(R.styleable.BarChartView_bar_color, Color.BLUE);
ta.recycle();
}
public void setData(List<Integer> data) {
mData = data;
mMaxValue = Collections.max(mData);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null || mData.size() == 0) {
return;
}
int width = getWidth();
int height = getHeight();
int barCount = mData.size();
float startX = width / 2 - (barCount * mBarWidth) / 2;
float startY = height - getPaddingBottom();
mPaint.setColor(mBarColor);
for (int i = 0; i < barCount; i++) {
float barHeight = ((float) mData.get(i) / mMaxValue) * (height - getPaddingTop() - getPaddingBottom());
canvas.drawRect(startX + i * mBarWidth, startY - barHeight, startX + (i + 1) * mBarWidth, startY, mPaint);
}
}
}
```
你可以在 XML 中添加该自定义 View:
```xml
<com.example.BarChartView
android:id="@+id/bar_chart"
android:layout_width="match_parent"
android:layout_height="200dp"
app:bar_width="30dp"
app:bar_color="#FF4081" />
```
然后在代码中设置数据即可:
```java
BarChartView barChart = findViewById(R.id.bar_chart);
List<Integer> data = Arrays.asList(5, 10, 15, 20, 25);
barChart.setData(data);
```
阅读全文