圆形图片(kotlin)

使用koelin 实现圆形的图片

说明

在这种需求中我们需要知道的首先就是圆形的图片她的宽和高是相等的,以宽或者高的一半为半径画圆就是我们要设计的圆,在将资源中的或者网络中的图片读取设置就OK了,
先看一下效果图这里写图片描述

在看代码

class CircularPictureView : ImageView {
    private var mRadius = 0 //图片的半径
    private lateinit var paint: Paint //画笔对象延迟加载   在使用的时候进行加载
    private var mScale = 0F //缩放比列

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //圆形的图片 我们应该让他的宽高是相等的
        val size = Math.min(measuredWidth, measuredHeight)
        mRadius = size.div(2)
        setMeasuredDimension(size, size)
    }

    override fun onDraw(canvas: Canvas?) {
        paint = Paint()
        val bitmap = drawableToBitmap(drawable)
        val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        mScale = bitmap?.height?.let { Math.min(it, bitmap?.width) }?.let { mRadius.times(2.0).div(it).toFloat() }!!
        val matrix = Matrix()
        matrix.setScale(mScale, mScale)
        bitmapShader.setLocalMatrix(matrix)

        paint.shader = bitmapShader
        //话圆形 质地昂中心点坐标 半径 画笔
        canvas?.drawCircle(mRadius.toFloat(), mRadius.toFloat(), mRadius.toFloat(), paint)
        /*
        *
        *  if (canvas != null) {
            canvas.drawCircle(mRadius.toFloat(), mRadius.toFloat(), mRadius.toFloat(),paint)
        }
        * */

    }

    /**
     * drawable 转成Bitmap的方法
     */
    private fun drawableToBitmap(drawable: Drawable?): Bitmap? {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }
        val width = drawable?.intrinsicWidth
        val height = drawable?.intrinsicHeight
        val bitmap = width?.let { height?.let { it1 -> Bitmap.createBitmap(it, it1, Bitmap.Config.ARGB_8888) } }
        val canvas = Canvas(bitmap)
        width?.let { height?.let { it1 -> drawable.setBounds(0, 0, it, it1) } }
        drawable?.draw(canvas)
        return bitmap
    }
}

完整的Demo

猜你喜欢

转载自blog.csdn.net/qq_32648731/article/details/77991400