我想使用调色板从图像中选择一种颜色。
首先,我将位图图像分成32个。 其次,我想用图像的代表色在回收站网格视图中显示它。
案例A。
切片32张图像并选择颜色
Bitmap org_bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
ArrayList<Integer> colors= new ArrayList<>();
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 8; j++) {
float box_width = width / 8;
float box_height = height / 4;
float x = startX + (box_width * (j - 1));
float y = startY + (box_height * (i - 1));
Bitmap spot_bitmap = Bitmap.createBitmap(image_bitmap, (int) x, (int) y, (int) box_width, (int) box_height);
Palette.from(spot_bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette p) {
// Use generated instance
Palette.Swatch vibrantSwatch = p.getVibrantSwatch();
if (vibrantSwatch != null) {
int rgb = vibrantSwatch.getRgb();
colors.add(rgb)
}
}
});
}
}
RecyclerView rv_colors= findViewById(R.id.rv_colors);
ImageColorAdpater adapter = new ImageGridAdpater(colors);
GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 8);
rv_colors.setLayoutManager(layoutManager);
rv_colors.setAdapter(adapter);
案例B。
切片32张图像(MainActivity.java)
Bitmap org_bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
ArrayList<Bitmap> bg_image = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 8; j++) {
float box_width = width / 8;
float box_height = height / 4;
float x = startX + (box_width * (j - 1));
float y = startY + (box_height * (i - 1));
Bitmap spot_bitmap = Bitmap.createBitmap(image_bitmap, (int) x, (int) y, (int) box_width, (int) box_height);
bg_image.add(spot_bitmap);
}
}
RecyclerView rv_images= findViewById(R.id.rv_images);
ImageGridAdpater adapter = new ImageGridAdpater(bg_image, getApplicationContext());
GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 8);
rv_images.setLayoutManager(layoutManager);
rv_images.setAdapter(adapter);
选择颜色并使用调色板显示(ImageGridAdpater .java)
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette p) {
// Use generated instance
Palette.Swatch vibrantSwatch = p.getVibrantSwatch();
if (vibrantSwatch != null) {
int rgb = vibrantSwatch.getRgb();
holder.item_color_grid_background_ll.setBackgroundColor(rgb);
}
}
});
holder.item_color_grid_ll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Palette palette = Palette.from(colors.get(position)).generate();
Palette.Swatch vibrantSwatch = palette.getVibrantSwatch();
if (vibrantSwatch != null) {
int rgb = vibrantSwatch.getRgb();
holder.item_color_grid_background_ll.setBackgroundColor(rgb);
}
}
});
实际上我想像情况A。但是它只是选择一种颜色。
所以,我尝试案例B。
案例B是 当使用Palette异步绑定视图时,我尝试设置背景。 并且如果无法设置颜色,则当我使用“调色板同步”单击项目设置背景时。
但是它不起作用。我该如何解决? 谢谢