android绘制一个条形图
时间: 2024-05-09 15:17:23 浏览: 80
以下是一个简单的Android条形图绘制示例:
1. 创建一个新的Android项目并在布局文件中添加一个FrameLayout,用于显示条形图。
2. 在Java代码中,编写以下代码来绘制条形图:
```java
public class BarChartView extends View {
private Paint mPaint;
private ArrayList<Bar> mBars = new ArrayList<Bar>();
public BarChartView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
// 绘制条形图背景
mPaint.setColor(Color.LTGRAY);
canvas.drawRect(0, 0, canvasWidth, canvasHeight, mPaint);
// 计算每个条形的宽度
int barCount = mBars.size();
int barWidth = canvasWidth / barCount;
// 绘制每个条形
for (int i = 0; i < barCount; i++) {
Bar bar = mBars.get(i);
int barHeight = (int) ((float) bar.value / 100 * canvasHeight);
int left = i * barWidth;
int right = left + barWidth;
int bottom = canvasHeight;
int top = canvasHeight - barHeight;
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
public void addBar(Bar bar) {
mBars.add(bar);
invalidate();
}
public static class Bar {
public String label;
public int value;
public Bar(String label, int value) {
this.label = label;
this.value = value;
}
}
}
```
3. 在Activity中,实例化BarChartView并添加条形:
```java
public class MainActivity extends AppCompatActivity {
private BarChartView mBarChartView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBarChartView = findViewById(R.id.bar_chart_view);
mBarChartView.addBar(new BarChartView.Bar("Bar 1", 50));
mBarChartView.addBar(new BarChartView.Bar("Bar 2", 75));
mBarChartView.addBar(new BarChartView.Bar("Bar 3", 25));
mBarChartView.addBar(new BarChartView.Bar("Bar 4", 90));
mBarChartView.addBar(new BarChartView.Bar("Bar 5", 60));
}
}
```
4. 运行应用程序,应该会显示一个包含五个条形的条形图。
阅读全文