自定义View--太极图

最近学习自定义view,一时兴起,做了个太极图,效果如下:

自定义View--太极图_第1张图片

绘制步骤:

  • 绘制一个圆心为屏幕中心,半径为r的黑色填充圆,添加宽为r,高为2r的矩形,取他两之间的差集,得到半圆。

自定义View--太极图_第2张图片

  • 绘制两个半径为r/2的小圆,一个取并集,一个取差集,得到黑色阴阳鱼。

自定义View--太极图_第3张图片

  • 绘制两个半径为r/8,圆心为小圆半径的更小圆,一个取并集,一个取差集,为阴阳鱼加上眼,不过白色阴阳鱼还没成型。

自定义View--太极图_第4张图片

  • 最后绘制大圆,并添加自旋转动画。

代码附上:

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint = new Paint();
        canvas.translate(mViewWidth / 2, mViewHeight / 2);//将原点移到屏幕中心,其实是移动画布

        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(5);
        mPaint.setAntiAlias(true);//抗锯齿

        float r = (float) (mViewWidth / 2 * 0.8);

        Path path1 = new Path();
        Path path2 = new Path();
        Path path3 = new Path();
        Path path4 = new Path();
        Path path5 = new Path();
        Path path6 = new Path();

        mPaint.setStyle(Paint.Style.FILL);
        path1.addCircle(0, 0, r, Path.Direction.CW);
        path2.addRect(0, -r, r, r, Path.Direction.CW);
        path3.addCircle(0, -r / 2, r / 2, Path.Direction.CW);
        path4.addCircle(0, r / 2, r / 2, Path.Direction.CCW);
        path5.addCircle(0, -r / 2, r / 8, Path.Direction.CW);
        path6.addCircle(0, r / 2, r / 8, Path.Direction.CW);

        path1.op(path2, Path.Op.DIFFERENCE);//取差集,即path1减去path2后剩下的部分,得到半圆
        path1.op(path3, Path.Op.UNION);//取并集,即两者相加
        path1.op(path4, Path.Op.DIFFERENCE);
        path1.op(path5, Path.Op.DIFFERENCE);
        path1.op(path6, Path.Op.UNION);

        canvas.drawPath(path1, mPaint);
        //绘制外圈
        mPaint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(0, 0, r, mPaint);
    }

自旋转代码:

        //添加旋转动画
        RotateAnimation animation = new RotateAnimation(0f, 360f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        animation.setInterpolator(linearInterpolator);
        animation.setDuration(5000);
        animation.setFillAfter(true);//保持最后状态
        animation.setRepeatMode(Animation.RESTART);
        animation.setRepeatCount(Animation.INFINITE);//无限循环
        taijiView.startAnimation(animation);

参考链接:https://www.gcssloop.com/customview/Path_Over

围观自定义view大佬博客:GcsSloop

我的GitHub:太极图

你可能感兴趣的:(Android,#自定义view)