Android 快速将一个Bitmap变成圆形或圆角矩形 kotlin

Android 快速将一个Bitmap变成圆形或圆角矩形 kotlin

  • Bitmap转圆形Drawable
  • Bitmap转圆角Drawable
  • 完事

Bitmap转圆形Drawable

新建文件CircleImageDrawable

class CircleImageDrawable(mBitmap: Bitmap) : Drawable() {
    private val mPaint: Paint
    private val mWidth: Int

    init {
        val bitmapShader = BitmapShader(
            mBitmap, TileMode.CLAMP,
            TileMode.CLAMP
        )
        mPaint = Paint()
        mPaint.isAntiAlias = true
        mPaint.shader = bitmapShader
        mWidth = mBitmap.width.coerceAtMost(mBitmap.height)
    }

    override fun draw(canvas: Canvas) {
        canvas.drawCircle(mWidth / 2.toFloat(), mWidth / 2.toFloat(), mWidth / 2.toFloat(), mPaint)
    }

    override fun getIntrinsicWidth(): Int {
        return mWidth
    }

    override fun getIntrinsicHeight(): Int {
        return mWidth
    }

    override fun setAlpha(alpha: Int) {
        mPaint.alpha = alpha
    }

    override fun setColorFilter(cf: ColorFilter?) {
        mPaint.colorFilter = cf
    }

    override fun getOpacity(): Int {
        return PixelFormat.TRANSLUCENT
    }
}

使用:

imgUser.setImageDrawable(CircleImageDrawable(bitmap))

Bitmap转圆角Drawable

新建文件RoundImageDrawable

class RoundImageDrawable(mBitmap: Bitmap, radius: Float) : Drawable() {

    private val mPaint: Paint
    private val mWidth: Int
    private val mRadius: Float

    init {
        val bitmapShader = BitmapShader(
            mBitmap, Shader.TileMode.CLAMP,
            Shader.TileMode.CLAMP
        )
        mPaint = Paint()
        mPaint.isAntiAlias = true
        mPaint.shader = bitmapShader
        mWidth = mBitmap.width.coerceAtMost(mBitmap.height)
        mRadius = radius
    }

    override fun draw(canvas: Canvas) {
        canvas.drawRoundRect(0f, 0f, mWidth.toFloat(), mWidth.toFloat(), mRadius, mRadius, mPaint)
    }

    override fun getIntrinsicWidth(): Int {
        return mWidth
    }

    override fun getIntrinsicHeight(): Int {
        return mWidth
    }

    override fun setAlpha(alpha: Int) {
        mPaint.alpha = alpha
    }

    override fun setColorFilter(cf: ColorFilter?) {
        mPaint.colorFilter = cf
    }

    override fun getOpacity(): Int {
        return PixelFormat.TRANSLUCENT
    }
}

使用:

imgUser.setImageDrawable(RoundImageDrawable(bitmap, 12f))

完事

你可能感兴趣的:(Android知识点,bitmap,android,圆形,圆角)