正式入坑 Kotlin,今后的自定义 View 不出意外都将会使用 Kotlin 实现,这次的 demo 放到了 Github 上哟,链接看文末。
这个颜色选择器分为 3 个部分,最外层白 - 中间选中色 - 黑,中层 红绿蓝渐变,中心显示选中颜色。
中间的红绿蓝渐变使用的 6 钟颜色渐变完成:
- mSweepGradient = SweepGradient((width / 2).toFloat(), (width / 2).toFloat(), intArrayOf(0xffff0000.toInt(), 0xffffff00.toInt(), 0xff00ff00.toInt(), 0xff00ffff.toInt(), 0xff0000ff.toInt(), 0xffff00ff.toInt(), 0xffff0000.toInt()), floatArrayOf(0f, 1 / 6f, 1 / 3f, 1 / 2f, 2 / 3f, 5 / 6f, 1f))
这个控件的难点是怎么知道手指触摸点的颜色,本来是想通过计算得出,因为红绿蓝的渐变是与角度相关的。但是想了想,计算量过大,于是换成了现在的方式。
首先,把红绿蓝的渐变画在一个 bitmap 上,然后通过手指触摸坐标,在 bitmap 上通过坐标获取触摸点的颜色。代码中就是 bufferCanvas 和 bitmap。就是传说中双缓存的套路。
控件默认等宽高(宽或高较小的为准),然后是说明一下变量,方便大家使用的时候修改。
使用的方式很简单,直接放在 xml 里面,然后通过代码获取选中颜色:
布局文件
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- android:layout_marginTop="10dp"
- android:layout_centerHorizontal="true"
- android:id="@+id/PPColorPicker21"
- android:layout_width="200dp"
- android:layout_height="200dp" />
- android:layout_centerInParent="true"
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="我是按钮"/>
获取颜色
- class MainActivity : Activity(){
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- button.setOnClickListener {
- button.setBackgroundColor(PPColorPicker21.chooseColor)
- button.text = "RGB:${PPColorPicker21.rgb}"
- }
- }
- }
最后总结一下遇到 Kotlin 的坑,这是我第二篇使用 Kotlin 自定义 View 的文章了,上一次是使用 AndroidStudio2.3,插件的方式。这一次是使用的 AS3.0 的第三个版本。环境搭建上完全没有遇坑,十分顺利。撸代码的时候,只有一个地方,一开始我继承的 View,实现了只有一个参数的构造方法(但是我 PPColorPicker 的默认构造方法是实现的 2 个参数的那个)
- class PPColorPicker(context: Context ? , attrs: AttributeSet ? =null) : View(context) {}
这样的。问题是在 Activity 中一直找不到控件,无论是使用 FindViewById 还是直接用 ID 都不行。一直报空指针异常。改成 2 个参数的就可以了。
最后还是要安利一下 Kotlin,特别是配合 Anko,可以大大提高开发效率。
Github 求 star。
来源: https://juejin.im/post/5a33153251882531b15b873e