Android 绘制变化的音频

通过自定义view来绘制一个不断变化的音频条形图

public class SoundWave extends View {
	private int mWidth, mHeight;
        // 默认矩形数量
	private int mRectCount = 10;

	private Paint paintRect;

	public SoundWave(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public SoundWave(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public SoundWave(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);

		if (widthMode == MeasureSpec.EXACTLY) {
			mWidth = widthSize;
		} else if (widthMode == MeasureSpec.AT_MOST) {
			throw new IllegalArgumentException(
					"width must be EXACTLY,you should set like android:width=\"200dp\"");
		}

		if (heightMode == MeasureSpec.EXACTLY) {
			mHeight = heightSize;
		} else if (widthMeasureSpec == MeasureSpec.AT_MOST) {

			throw new IllegalArgumentException(
					"height must be EXACTLY,you should set like android:height=\"200dp\"");
		}

		setMeasuredDimension(mWidth, mHeight);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		// view区域左右各留白1/5
		int mRectWidth = (int) (mWidth * 0.6 / mRectCount);
		int mRectHeight = mHeight - 20;
		for (int i = 0; i < mRectCount; i++) {
			// 随机产生矩形高度
			double mRandom = Math.random();
			float currentHeight = (float) (mHeight * mRandom);
			canvas.drawRect((float) (mWidth * 0.4 / 2 + mRectWidth * i),
					currentHeight, (float) (mWidth * 0.4 / 2 + mRectWidth
							* (i + 1)), mRectHeight, paintRect);
		}
		// 延迟0.3秒刷新一次
		postInvalidateDelayed(300);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		// 初始化先调用onSizeChanged
		int mRectWidth = (int) (mWidth * 0.6 / mRectCount);
		int mRectHeight = mHeight - 20;
		// 设置线性渐变
		LinearGradient mLinearGradient = new LinearGradient(0, 0, mRectWidth,
				mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
		paintRect = new Paint();
		paintRect.setStyle(Paint.Style.FILL);		
		paintRect.setShader(mLinearGradient);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值