1. 程式人生 > >自定義控制元件(顏色由綠色過渡到紅色的控制元件)

自定義控制元件(顏色由綠色過渡到紅色的控制元件)

先寫一個顏色的過度(由綠色過度到紅色)

**自定義控制元件的程式碼部分**

public class OneView extends View {

private Paint paint;
private Canvas mConvas;
private RectF rectF = new RectF(0, 0, 0, 0);;
private int lineWidth;


public OneView(Context context) {
    this(context,null);
}

public OneView(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs,-1);
}

public OneView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    setBackgroundResource(R.drawable.grident);
    lineWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, Resources.getSystem().getDisplayMetrics());
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.OneView);
    int count = typedArray.getInteger(R.styleable.OneView_count, 10);
    Log.e("count====",count+"");
    typedArray.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.mConvas=canvas;
    if(paint==null){
        paint = new Paint();
    }
    int height = getHeight();
    int width = getWidth();
    int subHeight = height / 10;
    //畫頂部覆蓋區域
    paint.setColor(Color.parseColor("#ffffff"));
    paint.setStyle(Paint.Style.FILL);
    canvas.drawRect(rectF,paint);

    //畫格子
    paint.setStrokeWidth(lineWidth);
    paint.setColor(Color.parseColor("#000000"));
    for (int i = 0; i < 9; i++) {
        canvas.drawLine(0,subHeight*(i+1),width,subHeight*(i+1),paint);
    }
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(lineWidth*2);
    canvas.drawRect(new RectF(0,0,width,height),paint);

}
public void setRect(int num){
    int height = getHeight();
    int width = getWidth();
    int subHeight = height / 10;
    int i = 10 - num;
    rectF.set(new RectF(0, 0, width, subHeight*i));
    invalidate();
}

} 佈局中 <com.xrd.nnnnn.OneView android:id="@+id/oneview" android:layout_width=“15dp” android:layout_height=“80dp” app:count=“8” android:layout_centerHorizontal=“true” android:layout_marginRight=“5dp” android:layout_marginTop=“5dp” android:layout_toLeftOf="@+id/myview" /> 程式碼中使用: oneView.setRect(integer);

顯示效果: 在這裡插入圖片描述