Android利用Paint自定義View實(shí)現(xiàn)進(jìn)度條控件方法示例
前言
View的三大流程:測(cè)量,布局,繪制,自定義View學(xué)的是啥?無(wú)非就兩種:繪制文字和繪制圖像。
我們?cè)谏弦黄恼隆?a target="_blank" href="http://www.dbjr.com.cn/article/128264.htm">Android繪圖之Paint的使用》中學(xué)習(xí)了Paint的基本用法,但是具體的應(yīng)用我們還沒(méi)有實(shí)踐過(guò)。從標(biāo)題中可知,本文是帶領(lǐng)讀者使用Paint,自定義一個(gè)進(jìn)度條控件。
效果圖

上圖就是本文要實(shí)現(xiàn)的效果圖。
實(shí)現(xiàn)過(guò)程
既然是自定義控件,本文的該控件是直接繼承View,然后重寫(xiě)View的onMeasure和onDraw方法來(lái)實(shí)現(xiàn)。其中onMeasure主要作用是測(cè)量控件的寬/高。而onDraw則是將界面繪制到屏幕上。
從效果的效果上看,我們需要自定義一些屬性,如:進(jìn)度度條的顏色、圓邊框的顏色、圓邊框的寬度和文本的大小等等。
具體的自定義屬性請(qǐng)看下面attrs.xml的代碼:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomProgressBar"> <attr name="roundProgressColor" format="color"></attr> <attr name="roundColor" format="color"></attr> <attr name="roundWidth" format="dimension"></attr> <attr name="textSize" format="dimension"></attr> <attr name="textColor" format="color"></attr> <attr name="max" format="integer"></attr> <attr name="textShow" format="boolean"></attr> <attr name="style"> <enum name="STROKE" value="0"></enum> <enum name="FILL" value="1"></enum> </attr> </declare-styleable> </resources>
接下來(lái)看本文的最重要部分,也就是自定義View
public class CustomProgressBar extends View {
private int max = 100;//總進(jìn)度
private int roundColor = Color.RED;//進(jìn)度圓弧的顏色
private float roundWidth = 10;//圓邊框?qū)挾?
private int roundProgressColor = Color.BLUE;//默認(rèn)的大圓環(huán)邊框顏色
private float textSize = 55;//文本大小
private int textColor = Color.GREEN;//文本默認(rèn)顏色
private boolean textShow = true;//是否展示文本
public static final int STROKE = 0;//描邊
public static final int FILL = 1;//填充
private int style = STROKE;//默認(rèn)描邊
private int progress;//進(jìn)度
private Paint mPaint;
private int mWidth = 200;//默認(rèn)控件寬度,wrap_content時(shí)候使用
private int mHeight = 200;//默認(rèn)控件高度,wrap_content時(shí)候使用
public CustomProgressBar(Context context) {
this(context, null);
}
public CustomProgressBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mPaint = new Paint();
if (attrs != null) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar);
max = typedArray.getInteger(R.styleable.CustomProgressBar_max, 100);
roundColor = typedArray.getColor(R.styleable.CustomProgressBar_roundColor, Color.BLUE);
roundProgressColor = typedArray.getColor(R.styleable.CustomProgressBar_roundProgressColor, Color.BLUE);
textColor = typedArray.getColor(R.styleable.CustomProgressBar_textColor, Color.GREEN);
textSize = typedArray.getDimension(R.styleable.CustomProgressBar_textSize, 55);
roundWidth = typedArray.getDimension(R.styleable.CustomProgressBar_roundWidth, 10);
textShow = typedArray.getBoolean(R.styleable.CustomProgressBar_textShow, true);
style = typedArray.getInt(R.styleable.CustomProgressBar_style, 0);
typedArray.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth,mHeight);
}else if (widthSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth,heightSpecSize);
}else if (heightSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(widthSpecSize,mHeight);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft - paddingRight;
int height = getHeight() - paddingBottom - paddingTop;
//畫(huà)默認(rèn)的大圓環(huán)
float radius = (float)Math.min(width,height)/2.0f;//中心坐標(biāo)點(diǎn)
mPaint.setColor(roundColor);
mPaint.setStyle(Paint.Style.STROKE);//描邊
mPaint.setStrokeWidth(roundWidth);//圓環(huán)邊的寬度
// if (style == STROKE){
// mPaint.setStrokeWidth(roundWidth);//圓環(huán)邊的寬度
// }
mPaint.setAntiAlias(true);
//(float cx, float cy, float radius, @NonNull Paint paint)
canvas.drawCircle(paddingLeft+width/2,paddingTop+height/2,radius,mPaint);
//畫(huà)進(jìn)度百分比
mPaint.setColor(textColor);
mPaint.setStrokeWidth(0);//圓環(huán)的寬度
mPaint.setTextSize(textSize);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
int percent = (int)(progress/(float)max * 100);
if(textShow && percent!=0 && style == STROKE){
//(@NonNull String text, float x, float y, @NonNull Paint paint)
canvas.drawText(percent+"%", (getWidth()-mPaint.measureText(percent+"%"))/2f,
//y公式: float baselineY = centerY + (fontMetrics.bottom-fontMetrics.top)/2 - fontMetrics.bottom
getWidth()/2f-(mPaint.descent()+mPaint.ascent())/2f,
mPaint);
}
//畫(huà)圓弧
//矩形區(qū)域,定義圓弧的形狀大小
//(float left, float top, float right, float bottom)
RectF oval = new RectF(paddingLeft, paddingTop, width+paddingLeft, height+paddingTop);
mPaint.setColor(roundProgressColor);
mPaint.setStrokeWidth(roundWidth);//圓環(huán)邊的寬度
switch (style){
case STROKE:
mPaint.setStyle(Paint.Style.STROKE);
//(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter,@NonNull Paint paint)
//useCenter:設(shè)置圓弧在繪畫(huà)的時(shí)候,是否經(jīng)過(guò)圓形
canvas.drawArc(oval , 0, 360*progress/max, false, mPaint);
break;
case FILL:
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
if(progress!=0)
canvas.drawArc(oval , 0, 360*progress/max, true, mPaint);
break;
default:
break;
}
}
public void setProgressWidth(int width) {
mWidth = width;
}
public void setProgressHeight(int height) {
mHeight = height;
}
public synchronized void setMax(int max) {
if (max < 0) {
throw new IllegalArgumentException("max不能小于0");
}
this.max = max;
}
public void setRoundColor(int roundColor) {
this.roundColor = roundColor;
}
public void setRoundWidth(float roundWidth) {
this.roundWidth = roundWidth;
}
public void setRoundProgressColor(int roundProgressColor) {
this.roundProgressColor = roundProgressColor;
}
public void setTextSize(float textSize) {
this.textSize = textSize;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public void setTextShow(boolean textShow) {
this.textShow = textShow;
}
public synchronized void setProgress(int progress) {
if (progress < 0) {
throw new IllegalArgumentException("progress不能小于0");
}
if (progress > max) {
progress = max;
}
if (progress <= max) {
this.progress = progress;
postInvalidate();
}
}
public synchronized int getMax() {
return max;
}
public int getRoundColor() {
return roundColor;
}
public float getRoundWidth() {
return roundWidth;
}
public int getRoundProgressColor() {
return roundProgressColor;
}
public int getTextColor() {
return textColor;
}
public boolean isTextShow() {
return textShow;
}
public synchronized int getProgress() {
return progress;
}
}
流程:初始化的時(shí)候會(huì)拿到自定義屬性,然后onMeasure方法中測(cè)量控件的寬和高,該方法主要處理了LayoutParams的wrap_content,當(dāng)wrap_content時(shí),默認(rèn)設(shè)置默認(rèn)寬/高,而不是讓控件占據(jù)整個(gè)屏幕,需要調(diào)用setMeasuredDimension方法測(cè)量。最后測(cè)量得到了控件的寬/高,調(diào)用onDraw方法將界面繪制到屏幕上,在onDraw方法繪制的時(shí)需要考慮padding的情況,如果不做padding處理,則padding將不起作用。
onDraw繪制流程:先繪制一個(gè)默認(rèn)的大圓環(huán),然后在圓中心繪制百分比的文本,最后再繪制一個(gè)進(jìn)度圓環(huán),進(jìn)度圓環(huán)會(huì)覆蓋底部的默認(rèn)大圓環(huán),這樣就達(dá)到顯示進(jìn)度的情況。
設(shè)置好畫(huà)筆之后,使用canvas.drawCircle繪制默認(rèn)的大圓環(huán),再次設(shè)置畫(huà)筆,使用canvas.drawText方法繪制文本;畫(huà)圓弧時(shí)需要定義一個(gè)矩形區(qū)域RectF,通過(guò)canvas.drawArc方法繪制。
繪制好之后,如何讓用戶(hù)看到進(jìn)度條在變化呢?其實(shí)就是通過(guò)setProgress方法里面的postInvalidate()方法,該方法會(huì)刷新界面,刷新界面時(shí)會(huì)調(diào)用onDraw,這樣就可以將進(jìn)度畫(huà)到屏幕上,進(jìn)度條不停的在變化。
使用
XML中使用
<?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-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.main.paint.PaintActivity"> <com.main.paint.CustomProgressBar android:id="@+id/progressbar" android:layout_width="200dp" android:layout_height="200dp" app:roundProgressColor="#FF0000" app:roundWidth="2dp" app:textColor="#FF0000" app:style="STROKE" android:padding="30dp" app:textSize="20dp"/> <com.main.paint.CustomProgressBar android:id="@+id/progressbar01" android:layout_width="200dp" android:layout_height="200dp" app:roundProgressColor="#FF0000" app:roundWidth="2dp" app:textColor="#FF0000" app:style="FILL" android:padding="30dp" app:textSize="20dp"/> </LinearLayout>
Activity代碼如下:
public class PaintActivity extends AppCompatActivity {
private CustomProgressBar mCustomProgressBar;
private CustomProgressBar mCustomProgressBar01;
private int progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paint);
mCustomProgressBar = (CustomProgressBar)this.findViewById(R.id.progressbar);
mCustomProgressBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
progress = 0;
while (progress <= 100) {
progress += 2;
mCustomProgressBar.setProgress(progress);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
mCustomProgressBar01 = (CustomProgressBar)this.findViewById(R.id.progressbar01);
mCustomProgressBar01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
progress = 0;
while (progress <= 100) {
progress += 2;
mCustomProgressBar01.setProgress(progress);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}
這樣就完成了一個(gè)自定義的進(jìn)度條控件,并且在onDraw方法中使用Paint將界面繪制出來(lái)。讀者可以自行實(shí)踐一把,加深對(duì)Paint的理解。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
ExpandListView實(shí)現(xiàn)下拉列表案例
這篇文章主要為大家詳細(xì)介紹了ExpandListView實(shí)現(xiàn)下拉列表案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
分享Android開(kāi)發(fā)中最有效率最快的循環(huán)代碼
分享Android開(kāi)發(fā)中最有效率最快的循環(huán)代碼,需要的朋友可以參考下2013-01-01
android實(shí)現(xiàn)常駐通知欄遇到的問(wèn)題及解決辦法
這篇文章主要介紹了android實(shí)現(xiàn)常駐通知欄遇到的問(wèn)題及解決辦法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
Android Activity 入門(mén)簡(jiǎn)介
Activity 是一個(gè)應(yīng)用組件,用戶(hù)可與其提供的屏幕進(jìn)行交互,以執(zhí)行撥打電話(huà)、拍攝照片、發(fā)送電子郵件或查看地圖等操作,這篇文章主要介紹了Android Activity入門(mén)基礎(chǔ)知識(shí),需要的朋友可以參考下2024-04-04
Android實(shí)現(xiàn)APP歡迎頁(yè)面簡(jiǎn)單制作思路
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)APP歡迎頁(yè)面簡(jiǎn)單制作思路,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
Android實(shí)現(xiàn)手機(jī)游戲隱藏虛擬按鍵
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)手機(jī)游戲隱藏虛擬按鍵,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
Android?WebView的使用與后退鍵處理詳細(xì)討論
在android開(kāi)發(fā)中我們有時(shí)候根據(jù)項(xiàng)目的需求多少會(huì)加載一些webview,加載webview,我們有時(shí)候會(huì)根據(jù)UI來(lái)自定義返回鍵,下面這篇文章主要給大家介紹了關(guān)于Android?WebView的使用與后退鍵處理的相關(guān)資料,需要的朋友可以參考下2024-04-04

