坚持学习每一天
爱生活,爱分享
如果您喜欢我的文章,可以点击关注,喜欢



先看看最终效果
首先新建一个类TaiJi集成VIew,并设置2个画笔
public class TaiJi extends View{
private Paint blackPaint;//黑色画笔
private Paint whitePaint;//白色画笔
public TaiJi(Context context) {//this在子类中调用构造方法
this(context,null);
}
public TaiJi(Context context, @Nullable AttributeSet attrs) {//this在子类中调用构造方法
this(context, attrs,0);
}
public TaiJi(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();//初始化
}
//初始化画笔
private void initPaint() {
blackPaint=new Paint();//创建画笔
blackPaint.setColor(Color.BLACK);//设置颜色
blackPaint.setAntiAlias(true);//抗锯齿
whitePaint=new Paint();
whitePaint.setColor(Color.WHITE);
whitePaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
然后在layout中写入该控件:
效果如图
再画之前我们分析一下怎么画:
1、先画两个半圆
2、再画两个半圆
3、最后画两个鱼眼
在onDraw中接着写
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width=canvas.getWidth();//确定画布宽度
int height=canvas.getHeight();//确定画布高度
canvas.translate(width/2,height/2);//将canvas坐标原点移动到画布中心
}
于是画布原点初始在左上方,经过偏移以后变到正中
开始绘制画图区域
RectF rectF=new RectF(-radius,-radius,radius,radius);//绘制一个矩形,绘制参数以此是左上右下
示意图
外面一圈是控件正常坐标下的绘制距离。当原点移动到正中心后图片绘制也将正中心算作原点。
开始画黑色半圆
/**
* rectF:代表绘制区域
* startAngle开始角度
* sweepAngle扫过角度
* useCenter是否经过圆心
* blackPaint画笔
*/
canvas.drawArc(rectF, 90, 180, true, blackPaint);//绘制黑色半圆
参数都比较好理解,就只有经过圆心一张图说明问题
黑色半圆效果
以此接着画
//绘制两个半圆
int radius = Math.min(width, height) / 2 - 100; //太极半径
RectF rect = new RectF(-radius, -radius, radius, radius); //绘制区域
canvas.drawArc(rect, 90, 180, true, blackPaing); //绘制黑色半圆
canvas.drawArc(rect, -90, 180, true, whitePaint); //绘制白色半圆
//绘制两个小圆
/**
* cx:圆心的x坐标。
cy:圆心的y坐标。
radius:圆的半径。
paint:绘制时所使用的画笔。
*/
int smallRadius = radius / 2;//小圆半径为大圆的一半
canvas.drawCircle(0, -smallRadius, smallRadius, blackPaing);
canvas.drawCircle(0, smallRadius, smallRadius, whitePaint);
//绘制鱼眼(两个更小的圆)
canvas.drawCircle(0, -smallRadius, smallRadius / 4, whitePaint);
canvas.drawCircle(0, smallRadius, smallRadius / 4, blackPaing);
效果如下
添加旋转效果
public void setRotate(float degrees) {
this.degrees = degrees;
invalidate();//重绘界面
}
在主界面中写
Handler handler=new Handler(){
private float degree=0;
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
taiji.setRotate(degree+=7);
this.sendEmptyMessageDelayed(0,1);//每1毫秒执行以此,每次角度+7
}
};
handler.sendEmptyMessageDelayed(0,1);//延时1毫秒执行
旋转太极完成,有兴趣的可以做一个可控制速度的电风扇。
传送门