import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* @author WangTao
* 自定义控件
*
*
*
* */
public class CustomView extends View implements Runnable{
// 上下文对象
private Context context;
// 初始化画笔对象
private Paint mpaint;
// 设置圆环的半径
private int radiu;
public CustomView(Context context) {
// TODO Auto-generated constructor stub
this(context,null);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context=context;
initPaint();
}
private void initPaint(){
// 实例化画笔并打开抗锯齿
mpaint=new Paint(Paint.ANTI_ALIAS_FLAG);
/*
*
* 画笔样式分三种:
* 1.Paint.Style.STROKE:描边
* 2.Paint.Style.FILL_AND_STROKE:描边并填充
* 3.Paint.Style.FILL:填充
*/
mpaint.setStyle(Paint.Style.STROKE);
// 设置画笔颜色为浅灰色
mpaint.setColor(Color.BLUE);
/*
* 设置描边的粗细,单位:像素px
* 注意:当setStrokeWidth(0)的时候描边宽度并不为0而是只占一个像素
*/
mpaint.setStrokeWidth(10);
}
//
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//canvas.drawCircle(cx, cy, radius, paint);
//xy表示圆心的xy坐标,第三个参数是圆的半径
canvas.drawCircle(500, 500, radiu, mpaint);
}
public void run() {
// TODO Auto-generated method stub
while(true){
try {
if(radiu<=200){
radiu+=10;
// 刷新View
postInvalidate();
}else{
radiu=0;
}
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void setRadiu(int radiu){
this.radiu=radiu;
// 重新绘制
invalidate();
}
}
package com.example.arrview;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
private CustomView mCustomView;// 我们的自定义View
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
mCustomView=(CustomView) findViewById(R.id.customView);
/*
* 开线程
*/
new Thread(mCustomView).start();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.arrview.CustomView
android:id="@+id/customView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</com.example.arrview.CustomView>
</RelativeLayout>