效果图
1.这次就不使用attrs.xml文件了,属性都在代码写死了
2.代码:
package com.example.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;
public class MusicStroke extends View {
private Paint mPaint;
private LinearGradient mLinearGradient;
private int mNumber;
private float mWidth;
public MusicStroke(Context context) {
this(context, null);
}
public MusicStroke(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MusicStroke(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < mNumber; i++) {
canvas.drawRect(i * mWidth, (float) (Math.random() * getMeasuredHeight() * 1f), (i + 1) * mWidth,
getMeasuredHeight(), mPaint);
/**
* 画mNumber个矩形,模拟音乐数据变化的随机效果
*/
}
postInvalidateDelayed((long) (Math.random() * 300));
/**
* 重复调用onDraw方法,间隔为0-300毫秒
*/
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mWidth == 0) {
mNumber = 30;
mPaint = new Paint();
mLinearGradient = new LinearGradient(0, 0, 0, getMeasuredHeight(),
new int[] { Color.parseColor("#ffbb33"), Color.RED, Color.parseColor("#ffbb33") }, null,
TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
/**
* 为矩形设置颜色渐变效果
*/
mWidth = getMeasuredWidth() / mNumber;
/**
* mWidth是每个矩形的高度
*/
}
}
}
3.模型图:
4.布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.customview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<com.example.customview.MusicStroke
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>