Android鬼点子 使用Kotlin编写的颜色选择器

正式入坑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里面,然后通过代码获取选中颜色:

布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <top.greendami.mykotlinapp.PPColorPicker
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:id="@+id/PPColorPicker21"
        android:layout_width="200dp"
        android:layout_height="200dp" />

    <Button
        android:layout_centerInParent="true"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是按钮"/>


</RelativeLayout>
复制代码

获取颜色

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值