我在 SO 上找到了这段代码,但我是新手,这个 Visualizer 类画得很好,但我想在垂直线之间放置空格,就像 Soundcloud 上的波形看起来一样。
public class VisualizerView extends View {
private static final int LINE_WIDTH = 6; // width of visualizer lines
private static final int LINE_SCALE = 7; // scales visualizer lines
private List<Float> amplitudes;
private int width; // width of this View
private int height; // height of this View
private Paint linePaint;
// constructor
public VisualizerView(Context context, AttributeSet attrs) {
super(context, attrs);
linePaint = new Paint(); // create Paint for lines
linePaint.setColor(Color.WHITE);
linePaint.setStrokeWidth(LINE_WIDTH);
}
// called when the dimensions of the View change
@Override
protected void onSizeChanged(int width, int height, int oldw, int oldh) {
this.width = width;
this.height = height;
this.amplitudes = new ArrayList<>(this.width / LINE_WIDTH);
}
public void clear() {
amplitudes.clear();
}
public void addAmplitude(float amplitude) {
// add newest to the amplitudes ArrayList
amplitudes.add(amplitude);
// if the power lines completely fill the VisualizerView
if (amplitudes.size() * LINE_WIDTH >= width) {
// remove oldest power value
amplitudes.remove(0);
}
}
// draw the visualizer with scaled lines representing the amplitudes
@Override
public void onDraw(Canvas canvas) {
// get the middle of the View
int middle = height / 2;
// start curX at zero
float curX = 0;
// for each item in the amplitudes ArrayList
for (float power : amplitudes) {
float scaledHeight = power / LINE_SCALE; // scale the power
// increase X by LINE_WIDTH
curX += LINE_WIDTH;
// draw a line representing this item in the amplitudes ArrayList
float startY = middle + scaledHeight / 2;
float stopY = middle - scaledHeight / 2;
canvas.drawLine(curX, startY, curX, stopY, linePaint);
}
}
}