package com.example.zhuang.tiaoxing;
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;
public class VolumeView extends View{
private int mWidth;//屏幕宽
private int mRectWidth;//矩形宽高
private int mRectHeight;
private Paint mPaint;
private int mRectCount;//矩形数量
private int offset = 5;//矩形之间空隙
private double mRandom;
private LinearGradient mLinearGradient;
public VolumeView(Context context) {
super(context);
initView();
}
public VolumeView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public VolumeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
//初始化布局的时候,先生成画笔
private void initView() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
mRectCount = 15;
}
@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);//矩形的宽
//LinearGradient实现闪动效果
mLinearGradient = new LinearGradient(
0,
0,
mRectWidth,
mRectHeight,
Color.YELLOW,
Color.GREEN,
Shader.TileMode.CLAMP
);
mPaint.setShader(mLinearGradient);//注意此句别忘写了
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i=0;i<mRectCount;i++){
mRandom = Math.random();
float currentHeight = (float)(mRectHeight*mRandom);
canvas.drawRect(
(float)(mWidth*0.4/2+mRectWidth*i + offset),
currentHeight,
(float)(mWidth*0.4/2+mRectWidth*(i+1)),
mRectHeight,
mPaint
);
}
postInvalidateDelayed(300);//每隔300毫秒绘画一次
}
}
自定义控件之——音频图
最新推荐文章于 2021-04-21 19:49:00 发布