如何使用RoundedBitmapDrawable仅为Bitmap顶部角设置圆角?
刚好我之前也碰到过这个需求,RoundedBitmapDrawable确实在旧版本里没有提供单独设置部分圆角的API,给你几个实用的解决方案:
方案1:自定义Canvas裁剪生成带顶部圆角的Bitmap
这个方法直接操作Bitmap生成新的带顶部圆角的图片,兼容性好,不依赖额外库,适合需要固定圆角Bitmap的场景。
代码示例(Kotlin):
fun getTopRoundedBitmap(originalBitmap: Bitmap, cornerRadius: Float): Bitmap { // 创建和原Bitmap尺寸一致的空白Bitmap val outputBitmap = Bitmap.createBitmap( originalBitmap.width, originalBitmap.height, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(outputBitmap) val paint = Paint(Paint.ANTI_ALIAS_FLAG) val path = Path() // 绘制顶部圆角的路径:左上角→右上角→右下角→左下角→闭合 path.moveTo(cornerRadius, 0f) path.lineTo(originalBitmap.width - cornerRadius, 0f) // 添加右上角圆角 path.quadTo( originalBitmap.width.toFloat(), 0f, originalBitmap.width.toFloat(), cornerRadius ) path.lineTo(originalBitmap.width.toFloat(), originalBitmap.height.toFloat()) path.lineTo(0f, originalBitmap.height.toFloat()) // 添加左上角圆角 path.lineTo(0f, cornerRadius) path.quadTo(0f, 0f, cornerRadius, 0f) // 裁剪画布,只保留路径内的区域 canvas.clipPath(path) // 在裁剪后的画布上绘制原Bitmap canvas.drawBitmap(originalBitmap, 0f, 0f, paint) return outputBitmap }
用法
直接将你的原Bitmap传入这个方法,得到处理后的Bitmap后设置给ImageView即可:
val roundedBitmap = getTopRoundedBitmap(yourOriginalBitmap, 16f) // 16f为圆角半径,按需调整 yourImageView.setImageBitmap(roundedBitmap)
方案2:使用MaterialShapeDrawable(AndroidX推荐)
如果你的项目已经引入了AndroidX的Material组件,这个方法更优雅,不需要直接操作Bitmap,还支持动态修改圆角参数。
代码示例(Kotlin):
val yourImageView = findViewById<ImageView>(R.id.your_image_view) val originalBitmap = ... // 你的原Bitmap // 创建ShapeAppearanceModel,仅设置顶部左右两个角的圆角 val shapeAppearanceModel = ShapeAppearanceModel() .toBuilder() .setTopLeftCorner(CornerFamily.ROUNDED, 16f) .setTopRightCorner(CornerFamily.ROUNDED, 16f) .build() // 创建MaterialShapeDrawable并绑定Bitmap val shapeDrawable = MaterialShapeDrawable(shapeAppearanceModel) shapeDrawable.paint.shader = BitmapShader( originalBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP ) // 将Drawable设置给ImageView yourImageView.background = null yourImageView.setImageDrawable(shapeDrawable)
优势
- 不需要重新生成Bitmap,性能更优
- 可以随时修改圆角半径,适合动态UI场景
- 符合Material Design规范
额外小技巧:AndroidX版本的RoundedBitmapDrawable2
如果你用的是AndroidX的androidx.core.graphics.drawable.RoundedBitmapDrawable2,其实它自带了设置部分圆角的API,一行代码就能解决:
val drawable = RoundedBitmapDrawableFactory.create(resources, originalBitmap) // radii数组顺序:左上x, 左上y, 右上x, 右上y, 右下x, 右下y, 左下x, 左下y drawable.cornerRadii = floatArrayOf(16f,16f, 16f,16f, 0f,0f, 0f,0f) yourImageView.setImageDrawable(drawable)
不过这个方法只适用于AndroidX环境,如果你还在使用旧的support库,还是推荐前面两个方案。
内容的提问来源于stack exchange,提问作者user1202032
相关产品推荐
相关产品推荐

