Android自定义view太极图

2018-10-10  本文已影响39人  猪爸爸Hulk

有幸看到了下边这篇文章,感觉很不错,自己比葫芦画瓢学习了一下,按照步骤把画的图形一步步拼凑,就实现了太极图,有兴趣的可以看原文链接,下边上图上源码
二十多行代码画太极

太极图

代码实现过程

class TigetView : View {

    private var viewSize = 0f
    private lateinit var blackPaint: Paint
    private lateinit var whitePaint: Paint
    private lateinit var rectF: RectF

    constructor(context: Context) : super(context) {
        initCustom(context, null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initCustom(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initCustom(context, attrs)
    }


    private fun initCustom(context: Context, attrs: AttributeSet?) {
        blackPaint = Paint().apply {
            color = Color.BLACK
            isAntiAlias = true
        }
        whitePaint = Paint().apply {
            color = Color.WHITE
            isAntiAlias = true
        }
        rectF = RectF()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        viewSize = Math.min(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)).toFloat()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.translate(viewSize / 2, viewSize / 2)
        canvas.drawColor(Color.GRAY)

        val radius = viewSize / 2 - paddingLeft
        rectF.set(-radius, -radius, radius, radius)
        canvas.drawArc(rectF, 90f, 180f, true, whitePaint)
        canvas.drawArc(rectF, -90f, 180f, true, blackPaint)

        val smallRadius = radius / 2
        canvas.drawCircle(0f, -smallRadius, smallRadius, whitePaint)
        canvas.drawCircle(0f, smallRadius, smallRadius, blackPaint)

        canvas.drawCircle(0f, -smallRadius, smallRadius / 4, blackPaint)
        canvas.drawCircle(0f, smallRadius, smallRadius / 4, whitePaint)
    }
}
上一篇下一篇

猜你喜欢

热点阅读