package com.zzw.qunyingzhuan2; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.util.AttributeSet; import android.view.View; /** * Created by zzw on 2016/7/11. * 描述: */ public class VoiceBarView extends View { private int mRectCount = 10; private int offset = 20; private int mWidth; private int mRectHeight; private int mRectWidth; private LinearGradient mLinearGradient; private Paint paint; public VoiceBarView(Context context) { this(context, null); } public VoiceBarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.GRAY); } public VoiceBarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < mRectCount; i++) { float currentHeight = (float) (Math.random() * mRectHeight); float left = (float) (mWidth * 0.2 + mRectWidth * i + offset); float top = currentHeight; float right = (float) (mWidth * 0.2 + mRectWidth * (i + 1)); // float right = left + mRectWidth; float bottom = mRectHeight; canvas.drawRect(left, top, right, bottom, paint); } postInvalidateDelayed(300); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = getWidth(); mRectHeight = getHeight(); mRectWidth = (int) (mWidth * 0.6 / mRectCount); mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP); paint.setShader(mLinearGradient); } }