android调色器的实现
最近在github上发现一个比较好用的调色器,写出来和大家分享下,用法也超级简单。先看效果图吧。
1.首先需要引用一个库,在app文件夹下的build.gradle里添加库“colorpicker”,我的颜色选择结果用一个矩形来展现,这里用到了circleimageview,故一起引用了。
implementation 'com.dingmouren.colorpicker:colorpicker:1.0.1'
implementation 'de.hdodenhof:circleimageview:2.1.0'
- activity_main.xml只是简单的布局了一个CircleImageView
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/colorAccent"
android:id="@+id/paint" android:layout_marginTop="32dp"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp"/>
</android.support.constraint.ConstraintLayout>
3.最后是MainActivity的实现,给CircleImageView注册点击事件,调起调色器,调色器有OnColorPickerListener回调,代码很简单。
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.dingmouren.colorpicker.ColorPickerDialog;
import com.dingmouren.colorpicker.OnColorPickerListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private boolean supportAlpha; //是否支持透明度
public static int myColor = Color.BLUE;
static CircleImageView paint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paint = findViewById(R.id.paint);
paint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ColorPickerDialog mColorPickerDialog = new ColorPickerDialog(
MainActivity.this,
myColor,
supportAlpha,
mOnColorPickerListener
).show();
}
});
}
public OnColorPickerListener mOnColorPickerListener = new OnColorPickerListener() {
@Override
public void onColorCancel(ColorPickerDialog dialog) {//取消选择的颜色
}
@Override
public void onColorChange(ColorPickerDialog dialog, int color) {//实时监听颜色变化
paint.setBackgroundColor(color);
}
@Override
public void onColorConfirm(ColorPickerDialog dialog, int color) {//确定的颜色
myColor = color;
paint.setBackgroundColor(color);
}
};
}