I am participating in the Mid-Autumn Festival Creative Submission contest, please see: Mid-Autumn Festival Creative Submission Contest for details

implementation

To achieve the moon glow effect, use the setMaskFilter() method of the Paint class, passing in the BlurMaskFilter object to achieve a Gaussian blur glow.

Thought analysis

First of all, we know total lunar eclipse, the moon is completely blocked out, but he will have a halo around, it should be a yellow gradient layer halo effect, through the MaskFilter we can set the halo radius and color, in order to make the effect more realistic our demo to glow with a layer of dynamic effect of the transparency change

Code thinking

Declaration of variables

var vWidth = 0f
    var vHeight = 0f
    var step =1
    var lightAlpht = 155f
    val paint = Paint().apply {
        maskFilter=BlurMaskFilter(500f,BlurMaskFilter.Blur.OUTER)
    }
Copy the code

Gets the height of the control

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        vWidth = w.toFloat()
        vHeight = h.toFloat()
    }
Copy the code

Mapping a total lunar eclipse

override fun onDraw(canvas: Canvas?). {
        super.onDraw(canvas)
        lightAlpht+=step// The opacity changes each time you draw
        paint.color= Color.argb((lightAlpht).toInt(),255.255.60)// The halo is yellow, we only do the opacity changecanvas? .run { drawCircle(vWidth /2, vHeight / 2.200f, paint)// Draw a circle in Paint with maskFilter set
        }
        invalidate()/ / redraw
        if(lightAlpht>255) {// If the transparency is greater than 255, the transparency begins to decrease
            step=-1
        }else if(lightAlpht<155) {// Start increasing transparency if the transparency is less than 155
            step=1}}Copy the code

Implementation effect

All the code

class MoonView(context: Context? , attrs: AttributeSet?) : View(context, attrs) {var vWidth = 0f
    var vHeight = 0f
    var step =1
    var lightAlpha = 155f
    private val paint = Paint().apply {
        maskFilter=BlurMaskFilter(500f,BlurMaskFilter.Blur.OUTER)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        vWidth = w.toFloat()
        vHeight = h.toFloat()
    }

    override fun onDraw(canvas: Canvas?). {
        super.onDraw(canvas)
        lightAlpha+=step
        paint.color= Color.argb((lightAlpha).toInt(),255.255.60) canvas? .run { drawCircle(vWidth /2, vHeight / 2.200f, paint)
        }
        invalidate()
        if(lightAlpha>=255){
            step=-3
        }else if(lightAlpha<=155){
            step=3}}}Copy the code