转载请注明:Android开发中文站 » 安卓自定义View实现图片上传进度显示(仿QQ)
demo下载地址:http://download.youkuaiyun.com/detail/baiyuliang2013/8690773
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class UpProView extends View {
private Paint mPaint;// 画笔
int width, height;
Context context;
int progress = 0;
public UpProView(Context context) {
this(context, null);
}
public UpProView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public UpProView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setAntiAlias(true); // 消除锯齿
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.parseColor("#70000000"));// 半透明
canvas.drawRect(0, 0, getWidth(), getHeight() - getHeight() * progress
/ 100, mPaint);
mPaint.setColor(Color.parseColor("#00000000"));// 全透明
canvas.drawRect(0, getHeight() - getHeight() * progress / 100,
getWidth(), getHeight(), mPaint);
mPaint.setTextSize(30);
mPaint.setColor(Color.parseColor("#FFFFFF"));
mPaint.setStrokeWidth(2);
Rect rect = new Rect();
mPaint.getTextBounds("100%", 0, "100%".length(), rect);// 确定文字的宽度
canvas.drawText(progress + "%", getWidth() / 2 - rect.width() / 2,
getHeight() / 2, mPaint);
}
/**
* 更新进度
*
* @param progress
*/
public void setProgress(int progress) {
this.progress = progress;
postInvalidate();
};
}
public class MainActivity extends Activity {
UpProView customView = null;
private final int SUCCESS = 0;
int progress = 0;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS:
Toast.makeText(MainActivity.this, "图片上传完成", Toast.LENGTH_SHORT)
.show();
customView.setVisibility(View.GONE);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customView = (UpProView) findViewById(R.id.customView);
// 模拟图片上传进度
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
customView.setProgress(i);
try {
Thread.sleep(200); // 暂停0.2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.sendEmptyMessage(SUCCESS);
}
}).start();
}
}
<FrameLayout
android:layout_width="150dp"
android:layout_height="200dp" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="@drawable/byl" />
<com.xr.uppro.UpProView
android:id="@+id/customView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>