自定义view(二)

        
public class CustomView extends TextView {
    private Paint mPaint;
    private int mProgress=0;//进度
    private int mStrokenWidth;//圆宽度
    private int mRadius;//圆半径
    private DisplayMetrics mMetrics;//屏幕参数
    private int centerX;//圆心所在x坐标
    private int centerY;//圆心所在y坐标
    private Rect mBounds;
	public CustomView(Context context) {
		this(context, null);
	}
	public CustomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
	}
	
	private void initPaint() {
		mPaint=new Paint();
		mBounds=new Rect();
		mMetrics=getResources().getDisplayMetrics();
		new Thread(){
			public void run() {
				while(true)
				{
					if(mProgress<360)
					{
						mProgress++;
					}else
					{
						
					}
					try {
						this.sleep(mProgress);
						postInvalidate();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		}.start();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		this.setText(mProgress*100/360+"%");
		this.setTextColor(Color.parseColor("#57C6FE"));
		this.setTextSize(20);
		this.setGravity(Gravity.CENTER);
		mRadius=200;
		centerX=mMetrics.widthPixels/2;
		centerY=mMetrics.heightPixels/2;
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Style.STROKE);
		mPaint.setColor(Color.RED);
		mPaint.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
		canvas.drawCircle(centerX, centerY, mRadius, mPaint);
		RectF rectf=new RectF(centerX-200, centerY-200, centerX+200, centerY+200);
		mPaint.setColor(Color.BLUE);
		canvas.drawArc(rectf, 0, mProgress, false, mPaint);
		//显示进度百分比
	/*	mPaint.setAntiAlias(false);
		mPaint.setTextSize(100);
		mPaint.setColor(Color.GREEN);
		mPaint.setAlpha(0x70);
		mPaint.setTypeface(Typeface.MONOSPACE);
		mPaint.setTextAlign(Align.CENTER);
		String text=mProgress*100/360+"%";
		mPaint.getTextBounds(text, 9, text.length(), mBounds);
		//计算文字高度
		float height=mBounds.height();
		canvas.drawText(text, centerX, centerY, mPaint);*/
		
	}
}

       关于绘制弧形的参数介绍:

@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		DisplayMetrics dm=getResources().getDisplayMetrics();
		Paint paint=new Paint();
		paint.setColor(Color.BLUE);
		paint.setStyle(Style.STROKE);
		paint.setAntiAlias(true);//打开抗锯齿
		paint.setStrokeWidth(20);
		/*
		 * 这个效果相当于画圆
		 * 第一个参数,代表矩形距离左边的x轴
		 * 第二个参数,代表矩形距离上边的y轴
		 * 第三个参数,代表矩形距离右边的x轴
		 * 第四个参数,代表矩形距离下边的y轴
		 */
		//RectF rectf=new RectF(dm.widthPixels/2,0, dm.heightPixels/2 , 100);
		RectF rectf=new RectF(dm.widthPixels/2-100, dm.heightPixels/2-100, dm.widthPixels/2+100, dm.heightPixels/2+100);
		//canvas.drawOval(rectf, paint);
		/*
		 * 第一个参数代表弧形所在的矩形范围
		 * 第二个参数代表弧形的开始弧度
		 * 第三个参数代表弧形的结束弧度
		 * 第四个参数没看出来有什么用
		 * 第五个就是画笔啦
		 */
		canvas.drawArc(rectf, 0, 360, false, paint);
	}


效果图:

自定义view(二)_第1张图片
      晚上有时间,再详细介绍里面的东西。

你可能感兴趣的:(android)