Android 常见的制作圆角方案

1,218 阅读1分钟

这是我参与更文挑战的第3天,活动详情查看:更文挑战

Android 常见的制作圆角方案都有什么?

  1. shape的方式

    缺点:shape 文件一般作为背景处理,抛开同样是增加布局层次以外,假设我们有成千上万个 Shape 文件,如何维护?不要觉得成千上万不可能,试想一下。这个白底4圆角一个 Shape,那个黄底4圆角一个 Shape,又来了一个白底10圆角,又是一个Shape文件。更 容易出现的是,开发中很多童鞋一起维护,可能张三和李四写的都是白底10圆角,仅仅 是名字不一样,又来了一个 Shape。oh,想想都很可怕对吧?

  2. 自定义Drawable 如ShadowDrawable GradientDrawable ` /**

    • 背景drawable,文本颜色 */ private fun initState() { states[0] = intArrayOf(android.R.attr.state_enabled, android.R.attr.state_pressed) states[1] = intArrayOf(android.R.attr.state_enabled) states[2] = intArrayOf()

      backgroundColors[0] = pressBackgroundColor backgroundColors[1] = normalBackgroundColor backgroundColors[2] = unableBackgroundColor

      textColors[0] = textPressColor textColors[1] = textNormalColor textColors[2] = textNormalColor

    }

    private fun getStateListDrawable(): StateListDrawable { val stateListDrawable = StateListDrawable() stateListDrawable.addState(states[0], pressBackgroundColor.toDrawable) stateListDrawable.addState(states[1], normalBackgroundColor.toDrawable) stateListDrawable.addState(states[2], unableBackgroundColor.toDrawable) return stateListDrawable }

    private val (Int).toDrawable: GradientDrawable get() { val gradientDrawable = GradientDrawable() //ColorStateList 中定义的默认 Item 一定要放在最下面 gradientDrawable.setColor(this) gradientDrawable.cornerRadius = circleRadius.dp2px(this@DonButton.context) return gradientDrawable }`

  3. 使用ViewOutlineProvider裁剪(Android5.0以上)

  4. 参照Glide办法,使用BitmapShader,将原始的内容画到一个临时的bitmap上,使用BitmapShaper将它设置成画笔,

然后通过canvas画一个圆角区域,如:

1.jpg 5.cardview控件

  1. PorterDuffXfermode

它一共有18种模式(注意是模式不是效果,不同的模式通过不同的写法最终出来的效果也可能是一样),可以实现圆角效果的Mode,通常有这三种:

SRC_IN SRC_ATOP MULTIPLY 但我们一般用SRC_IN。