天天看點

圓形圖檔

通過BitmapShader來設定圖檔圓形。

直接上代碼

package com.mark.jetpackpaging.view

import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatImageView
import com.mark.jetpackpaging.R
import kotlin.math.min

class CircleDrawable : AppCompatImageView {
    var srcSource: Drawable
    var mWidth = 0
    var mHeight = 0
    private val mPaint = Paint()

    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
    ) {
        val obtainAttributes = resources.obtainAttributes(attrs, R.styleable.Circleimage)
        srcSource = obtainAttributes.getDrawable(R.styleable.Circleimage_src_source)!!
        obtainAttributes.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (widthMode == MeasureSpec.EXACTLY) {
            mWidth = widthSize
        } else {
            mWidth = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                200f,
                resources.displayMetrics
            ).toInt()
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            mHeight = heightSize
        } else {
            mHeight = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                200f,
                resources.displayMetrics
            ).toInt()
        }
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val bitmap: Bitmap = getBitmapFromDrawable(srcSource)
        val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        mPaint.shader = bitmapShader
        val radius = min(mWidth, mHeight) / 2
        val centerX = mWidth / 2
        val centerY = mHeight / 2
        canvas?.drawCircle(centerX.toFloat(), centerY.toFloat(), radius.toFloat(), mPaint)
    }

    private fun getBitmapFromDrawable(drawable: Drawable): Bitmap {
        val createBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(createBitmap)
        drawable.setBounds(0, 0, mWidth, mHeight)
        drawable.draw(canvas)
        return createBitmap
    }
}
           

使用的時候和使用ImageView一樣,設定圖檔資源使用 app:src_source="@drawable/image_head"

繼續閱讀