自定义View之渐变色圆形进度条

先展示下效果图:

这里写图片描述

然后按照自定义view的步骤来实现。

我们需要将目标定义清楚:
目标是渐变色圆形进度条,那么,使用canvas画弧形是基础了,另外是渐变色的效果,这里使用LinearGradient来实现。
既然是提供一个进度条,那么,是需要自定义View的用户来进行设置进度值的。
另外,将渐变色的接口也提供出来了,这样,用户就可以根据需要自己定义喜欢的渐变色效果。
还有view的大小,使用直径来表示。
最后,要展示进度条如何使用,用了一个定时器,每秒推进一次进度。

下面来具体实现:

1、自定义View的属性

在values下面新建一个attr.xml,现在里面定义我们的属性,

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="diameter" format="dimension" />

    <declare-styleable name="CircleProgressView">
        <attr name="diameter" />
    </declare-styleable>

</resources>

2、在View的构造方法中获得我们自定义的属性

    public CircleProgressView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        /**
         * 获得我们所定义的自定义样式属性
         */
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleProgressView, defStyle, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++)
        {
            int attr = a.getIndex(i);
            switch (attr)
            {
            case R.styleable.CircleProgressView_diameter:
                // 默认设置为40dp
                mDiameter = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_SP, 40, getResources().getDisplayMetrics()));
                break;          
            }
        }
        a.recycle();

        mPaint = new Paint();
        rect = new RectF();
        progressValue=0;
    }

3、重写onMeasure

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = 0;
        int height = 0;

        //设置直径的最小值
        if(mDiameter<=40){
            mDiameter=40;
        }
        height=mDiameter;
        width=mDiameter;

        Log.i("customView","log: w="+width+" h="+height);
        setMeasuredDimension(width, height);
    }

4、重写onDraw

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int mWidth = getMeasuredWidth();
        int mHeight = getMeasuredHeight();

        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth((float) mWidth/10 );
        mPaint.setStyle(Style.STROKE);
        mPaint.setStrokeCap(Cap.ROUND);
        mPaint.setColor(Color.TRANSPARENT);

        rect.set(20, 20, mWidth - 20, mHeight - 20);
        canvas.drawArc(rect, 0, 360, false, mPaint);
        mPaint.setColor(Color.BLACK);   

        float section = ((float)progressValue) / 100;
        int count = mColors.length;
        int[] colors = new int[count];
        System.arraycopy(mColors, 0, colors, 0, count);         

        LinearGradient shader = new LinearGradient(3, 3, mWidth - 3 , mHeight - 3, colors, null,
                Shader.TileMode.CLAMP);
        mPaint.setShader(shader);

        canvas.drawArc(rect, 0, section * 360, false, mPaint);
    }

5、提供对外接口

这里有两个对外接口,一个是用于获取新的进度值的:

    public void setProgressValue(int progressValue){

        this.progressValue = progressValue;
        Log.i("customView","log: progressValue="+progressValue);            

    }

另外一个是用于设置渐变色的,这里我是定义了4种颜色,经过测试效果比较好:

    public void setColors(int[] colors){

        mColors = colors;
        Log.i("customView","log: progressValue="+progressValue);            

    }

6、中布局文件中使用

在布局文件中我定义了5个view,中间一个大的,四角四个小的,这样效果比较炫:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.customview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.customview.view.CircleProgressView
        android:id="@+id/circle_progress_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"            
        android:layout_centerInParent="true" 
        android:padding="10dp"
        custom:diameter="200dp"              
        /> 

    <com.customview.view.CircleProgressView
        android:id="@+id/circle_progress_view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"            
        android:layout_toLeftOf="@id/circle_progress_view1"               
        android:layout_below="@id/circle_progress_view1"    
        android:padding="10dp"
        custom:diameter="80dp"  
        /> 

     <com.customview.view.CircleProgressView
        android:id="@+id/circle_progress_view3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/circle_progress_view1"
        android:layout_below="@id/circle_progress_view1"                   
        android:layout_centerHorizontal="true"
        android:padding="10dp"  
        custom:diameter="80dp"      
        /> 

     <com.customview.view.CircleProgressView
        android:id="@+id/circle_progress_view4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/circle_progress_view1"
        android:layout_above="@id/circle_progress_view1"                   
        android:layout_centerHorizontal="true"
        android:padding="10dp"
        custom:diameter="80dp"      
        /> 

     <com.customview.view.CircleProgressView
        android:id="@+id/circle_progress_view5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/circle_progress_view1"
        android:layout_above="@id/circle_progress_view1"                   
        android:layout_centerHorizontal="true"
        android:padding="10dp"  
        custom:diameter="80dp"      
        /> 

</RelativeLayout>

7、在activity中使用

主要是一个定时器的使用,来推进进度条,另外,是渐变色的颜色初值设置:

package com.customview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.customview.view.CircleProgressView;

import android.app.Activity;
import android.graphics.Color;

public class MainActivity extends Activity
{
    CircleProgressView circle_progress_view1;
    CircleProgressView circle_progress_view2;
    CircleProgressView circle_progress_view3;
    CircleProgressView circle_progress_view4;
    CircleProgressView circle_progress_view5;

    int progressValue=0;    

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏

        setContentView(R.layout.activity_main);

        circle_progress_view1 = (CircleProgressView)findViewById(R.id.circle_progress_view1);
        circle_progress_view2 = (CircleProgressView)findViewById(R.id.circle_progress_view2);
        circle_progress_view3 = (CircleProgressView)findViewById(R.id.circle_progress_view3);
        circle_progress_view4 = (CircleProgressView)findViewById(R.id.circle_progress_view4);
        circle_progress_view5 = (CircleProgressView)findViewById(R.id.circle_progress_view5);

        //第一个使用默认颜色,第二三个使用指定颜色,另外2个使用随机颜色
        int[] colors;
        colors=new int[]{ 0xffc42c1b, 0xfffeea08, 0xff04aafc, 0xff15e078};
        circle_progress_view2.setColors( colors);
        colors=new int[]{ 0xffffffff, 0xffaaaaaa, 0xff555555, 0xff000000};      
        circle_progress_view3.setColors( colors);       
        circle_progress_view4.setColors( randomColors());
        circle_progress_view5.setColors( randomColors());

        timer.schedule(task, 1000, 1000); // 1s后执行task,经过1s再次执行          
    }

    Handler handler = new Handler() {  
        public void handleMessage(Message msg) {  
            if (msg.what == 1) {  
                Log.i("log","handler : progressValue="+progressValue);

                //通知view,进度值有变化
                circle_progress_view1.setProgressValue(progressValue*3);
                circle_progress_view1.postInvalidate();
                circle_progress_view2.setProgressValue(progressValue*5/2);
                circle_progress_view2.postInvalidate();
                circle_progress_view3.setProgressValue(progressValue*2);                
                circle_progress_view3.postInvalidate();
                circle_progress_view4.setProgressValue(progressValue*3/2);              
                circle_progress_view4.postInvalidate();
                circle_progress_view5.setProgressValue(progressValue*1);                
                circle_progress_view5.postInvalidate();

                progressValue+=1;
                if(progressValue>100){
                    timer.cancel();
                }
            }  
            super.handleMessage(msg);              
        };  
    };  

    private int[] randomColors() {
        int[] colors=new int[4];

        Random random = new Random();
        int r,g,b;
        for(int i=0;i<4;i++){
            r=random.nextInt(256);
            g=random.nextInt(256);
            b=random.nextInt(256);
            colors[i]=Color.argb(255, r, g, b);
            Log.i("customView","log: colors["+i+"]="+Integer.toHexString(colors[i]));
        }

        return colors;
    }

    Timer timer = new Timer();  
    TimerTask task = new TimerTask() {  

        @Override  
        public void run() {  
            // 需要做的事:发送消息  
            Message message = new Message();  
            message.what = 1;  
            handler.sendMessage(message);  
        }  
    };  

}

至此,完美收工。
我是实现了一个渐变色圆形进度条,渐变色的颜色初值可以指定,进度条的值也是由用户来指定,本例中是使用定时器来推进的,每个进度条的进度控制不一致,颜色不一样,位置不一样,组合起来,效果很炫哦!

完整代码见如下地址:

http://download.csdn.net/detail/lintax/9623574

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个简单的圆形进度条自定义View实现: ```java public class CircleProgressBar extends View { private float mProgress = 0; // 当前进度值 private float mMax = 100; // 最大进度值 private int mCircleWidth = 10; // 圆环宽度 private int mCircleColor = Color.GRAY; // 圆环颜色 private int mProgressColor = Color.BLUE; // 进度条颜色 private Paint mPaint; public CircleProgressBar(Context context) { super(context); init(); } public CircleProgressBar(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar); mCircleWidth = ta.getDimensionPixelSize(R.styleable.CircleProgressBar_circleWidth, 10); mCircleColor = ta.getColor(R.styleable.CircleProgressBar_circleColor, Color.GRAY); mProgressColor = ta.getColor(R.styleable.CircleProgressBar_progressColor, Color.BLUE); ta.recycle(); init(); } private void init() { mPaint = new Paint(); mPaint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int centerX = getWidth() / 2; int centerY = getHeight() / 2; int radius = getWidth() / 2 - mCircleWidth / 2; // 画圆环 mPaint.setColor(mCircleColor); mPaint.setStrokeWidth(mCircleWidth); mPaint.setStyle(Paint.Style.STROKE); canvas.drawCircle(centerX, centerY, radius, mPaint); // 画进度条 mPaint.setColor(mProgressColor); mPaint.setStrokeWidth(mCircleWidth); mPaint.setStyle(Paint.Style.STROKE); RectF rectF = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); canvas.drawArc(rectF, -90, 360 * mProgress / mMax, false, mPaint); } public void setProgress(float progress) { mProgress = progress; invalidate(); } public void setMax(float max) { mMax = max; invalidate(); } } ``` 其中,我们可以设置圆环的宽度、圆环颜色、进度条颜色等属性。在onDraw()方法中,我们先画出圆环,然后再画出进度条进度条的弧度根据当前进度值和最大进度值计算得出。 使用时,可以在布局文件中添加如下代码: ```xml <com.example.customview.CircleProgressBar android:id="@+id/circle_progress_bar" android:layout_width="wrap_content" android:layout_height="wrap_content" app:circleColor="#FFA500" app:circleWidth="20dp" app:progressColor="#00BFFF" /> ``` 然后在代码中设置进度值即可: ```java CircleProgressBar circleProgressBar = findViewById(R.id.circle_progress_bar); circleProgressBar.setMax(100); circleProgressBar.setProgress(50); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值