第一篇写surfaceView,其实也没什么特别的用意,单纯是因为最近在研究这个。多的不说,先上效果图;
通过绘画技巧和角度的控制画出圆环做背景,主要的思路是利用View的drawArc画扇形的方法,中间再画一个白色的圆,再根据区域涂色,就能画出圆环图形
public class DrawRound extends SurfaceView implements SurfaceHolder.Callback,Runnable{
float rooterX=500;
float rooterY=800;
float rooterR=400;
float cornerAll=360;
float cornerInit=0;
private int[] colorC={
Color.BLACK,
Color.BLUE,
Color.CYAN,
Color.DKGRAY,
Color.GRAY,
Color.GREEN,
Color.LTGRAY,
Color.RED,
Color.YELLOW
};
@Override
public void surfaceCreated(SurfaceHolder arg0) {
flag = true;
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
rooterX=width/2;
rooterY=height/2-100;
thread = new Thread(this);
thread.start();
}
//提供给外部的接口用于修改色环上的颜色条目,默认是4
public void drawChange(int count){
this.count=count;
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
//创建Paint数组,长度由count即可有外部决定
Paint[] paints=new Paint[count];
RectF rects=new RectF(rooterX-rooterR, rooterY-rooterR, rooterX+rooterR,rooterY+rooterR);
Paint paint=null;
//确定画布的数据
for(int i=0;i<count;i++){
paint=new Paint();
paint.setColor(colorC[i%9]);
paint.setAntiAlias(true);
paint.setStyle(Style.FILL_AND_STROKE);
paints[i]=paint;
}
paintWhite=new Paint();
paintWhite.setColor(Color.WHITE);
paintWhite.setAntiAlias(true);
paintWhite.setStyle(Style.FILL_AND_STROKE);
paintLine=new Paint();
paintLine.setColor(Color.WHITE);
paintLine.setAntiAlias(true);
paintLine.setStyle(Style.FILL_AND_STROKE);
canvas=this.holder.lockCanvas();
//界面的底色设置为白色
this.canvas.drawColor(Color.WHITE);
this.canvas.drawCircle(rooterX, rooterY, rooterR, paintWhite);
this.canvas.drawLine(rooterX, rooterY-rooterr, rooterX, rooterY-rooterR, paintLine);
this.canvas.drawLine(rooterX, rooterY+rooterr, rooterX, rooterY+rooterR, paintLine);
this.canvas.drawLine(rooterX-rooterr, rooterY, rooterX-rooterR, rooterY, paintLine);
this.canvas.drawLine(rooterX+rooterr, rooterY, rooterX+rooterR, rooterY, paintLine);
//通过外部的数据count 来画扇形,cornerAll/count是每个扇形划过的角度大小;
float cornerA=0;
for(int i=0;i<count;i++){
this.canvas.drawArc(rects, cornerA, cornerAll/count, true, paints[i]);
cornerA=cornerA+cornerAll/count;
}
//画中心的圆环
this.canvas.drawCircle(rooterX, rooterY, rooterr, paintWhite);
}
}
MainActivity的代码其实很简单,就是一个btn,设置点击效果,XML代码是直接把包名带入
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawR=(DrawRound)findViewById(R.id.my_surface_view);
Button change_btn=(Button)findViewById(R.id.change_btn);
change_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int ran=(int)(1+Math.random()*10);
drawR.drawChange(ran);
}
});
}
}