Палитра цветов Android

Я ищу структуру выбора цвета, которая может возвращать цвет HEX при выборе.

Я просмотрел это, задаваясь вопросом, есть ли какая-то другая библиотека, которую я могу использовать.


person Harsha M V    schedule 08.08.2011    source источник


Ответы (8)


попробуйте эти проекты с открытым исходным кодом, которые могут вам помочь

https://github.com/QuadFlask/colorpicker

person dharam    schedule 08.08.2011
comment
ссылки уже не работают - person Massimo; 10.08.2016
comment
Эта библиотека также включает хороший цветовой круг и средство выбора палитры: github.com/eltos/SimpleDialogFragments. - person Philipp; 04.03.2017

Я знаю, что вопрос старый, но если кто-то ищет отличный новый инструмент выбора цвета для Android, в котором используется дизайн материалов, я создал отличный проект из github и создал простой в использовании диалог выбора цвета для Android.

Это проект: Палитра цветов для Android

Диалоговое окно выбора цвета Android

введите здесь описание изображения

КАК ЭТО ИСПОЛЬЗОВАТЬ

Добавление библиотеки в ваш проект

Артефакт aar доступен в репозитории jcenter. Объявите репозиторий и зависимость в файле build.gradle.

(корень)

repositories {
    jcenter()
}

(модуль)

dependencies {
    compile 'com.pes.materialcolorpicker:library:1.0.2'
}

Используйте библиотеку

Создание диалогового объекта выбора цвета

final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);

defaultColorR, defaultColorG, defaultColorB — это 3 целых числа (значение 0-255) для инициализации палитры цветов с вашим пользовательским значением цвета. Если вы не хотите начинать с цвета, установите для них значение 0 или используйте только первый аргумент.

Затем покажите диалоговое окно (когда и где вы хотите) и сохраните выбранный цвет.

/* Show color picker dialog */
cp.show();

/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);

okColor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            
        /* You can get single channel (value 0-255) */
        selectedColorR = cp.getRed();
        selectedColorG = cp.getGreen();
        selectedColorB = cp.getBlue();
            
        /* Or the android RGB Color (see the android Color class reference) */
        selectedColorRGB = cp.getColor();

        cp.dismiss();
    }
});

Это все :)

person Simone Pessotto    schedule 26.07.2015
comment
классный друг :D - person Harsha M V; 26.07.2015
comment
Спасибо :) Если у вас есть какие-либо предложения, скажите мне. Мне это нужно было две недели назад, поэтому я сделал это сам, надеюсь, это будет полезно кому-то еще. - person Simone Pessotto; 26.07.2015
comment
@SimonePessotto setOnclicklistner на кнопке Хорошо, это дает исключение нулевого указателя. Помогите мне. - person CLIFFORD P Y; 01.02.2016
comment
@Clifford Клиффорд, я проверю ... Что именно ты сделал? - person Simone Pessotto; 01.02.2016
comment
А также скажите, для какой версии андроида вы разрабатываете - person Simone Pessotto; 01.02.2016
comment
@Clifford Клиффорд, вы пытались настроить слушателя, прежде чем показывать палитру цветов? Поскольку вы не можете, вам нужно показать палитру цветов, а затем установить прослушиватель на кнопку. Кстати, откройте новый вопрос, возможно, и вставьте код :) Я здесь, если вам нужна помощь - person Simone Pessotto; 01.02.2016
comment
о, хорошо... Спасибо, @SimonePessotto. ColorPicker прост и хорош. Еще раз спасибо :) - person CLIFFORD P Y; 01.02.2016
comment
Это больше не работает. Я не могу добавить его в свой проект. - person Danish Ajaib; 24.05.2018
comment
@DanishAjaib, если вы столкнулись с какими-либо ошибками, откройте проблему в проекте Github. Также обратите внимание, что ответ устарел, и тем временем проект изменил некоторый вызов API/функции. - person Simone Pessotto; 24.05.2018
comment
Пожалуйста, @SimonePessotto обновите зависимости: скомпилируйте 'com.pes.materialcolorpicker:library:1.2.5' - person nicomonjelat; 01.09.2020
comment
@nicomonjelat, что ты имеешь в виду? Не стесняйтесь отправить запрос на включение, если хотите :) - person Simone Pessotto; 02.09.2020
comment
@SimonePessotto, извини. Я хотел обновить зависимости модуля в этом ответе. Они устарели. Большое спасибо! - person nicomonjelat; 07.09.2020

Вы можете использовать следующий код, он будет выглядеть так же, как http://code.google.com/p/color-picker-view/

public class ColorPickerDialog extends Dialog {

public interface OnColorChangedListener {
    void colorChanged(String key, int color);
}

private OnColorChangedListener mListener;
private int mInitialColor, mDefaultColor;
private String mKey;

private static class ColorPickerView extends View {
    private Paint mPaint;
    private float mCurrentHue = 0;
    private int mCurrentX = 0, mCurrentY = 0;
    private int mCurrentColor, mDefaultColor;
    private final int[] mHueBarColors = new int[258];
    private int[] mMainColors = new int[65536];
    private OnColorChangedListener mListener;

    ColorPickerView(Context c, OnColorChangedListener l, int color,
            int defaultColor) {
        super(c);
        mListener = l;
        mDefaultColor = defaultColor;

        // Get the current hue from the current color and update the main
        // color field
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        mCurrentHue = hsv[0];
        updateMainColors();

        mCurrentColor = color;

        // Initialize the colors of the hue slider bar
        int index = 0;
        for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
                                                    // (#f0f)
        {
            mHueBarColors[index] = Color.rgb(255, 0, (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
                                                    // (#00f)
        {
            mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
                                                    // blue (#0ff)
        {
            mHueBarColors[index] = Color.rgb(0, (int) i, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
                                                    // green (#0f0)
        {
            mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
                                                    // (#ff0)
        {
            mHueBarColors[index] = Color.rgb((int) i, 255, 0);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
                                                    // (#f00)
        {
            mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
            index++;
        }

        // Initializes the Paint that will draw the View
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setTextSize(12);
    }

    // Get the current selected color from the hue bar
    private int getCurrentMainColor() {
        int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
        int index = 0;
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255, 0, (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255 - (int) i, 0, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(0, (int) i, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(0, 255, 255 - (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb((int) i, 255, 0);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255, 255 - (int) i, 0);
            index++;
        }
        return Color.RED;
    }

    // Update the main field colors depending on the current selected hue
    private void updateMainColors() {
        int mainColor = getCurrentMainColor();
        int index = 0;
        int[] topColors = new int[256];
        for (int y = 0; y < 256; y++) {
            for (int x = 0; x < 256; x++) {
                if (y == 0) {
                    mMainColors[index] = Color.rgb(
                            255 - (255 - Color.red(mainColor)) * x / 255,
                            255 - (255 - Color.green(mainColor)) * x / 255,
                            255 - (255 - Color.blue(mainColor)) * x / 255);
                    topColors[x] = mMainColors[index];
                } else
                    mMainColors[index] = Color.rgb(
                            (255 - y) * Color.red(topColors[x]) / 255,
                            (255 - y) * Color.green(topColors[x]) / 255,
                            (255 - y) * Color.blue(topColors[x]) / 255);
                index++;
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
        // Display all the colors of the hue bar with lines
        for (int x = 0; x < 256; x++) {
            // If this is not the current selected hue, display the actual
            // color
            if (translatedHue != x) {
                mPaint.setColor(mHueBarColors[x]);
                mPaint.setStrokeWidth(1);
            } else // else display a slightly larger black line
            {
                mPaint.setColor(Color.BLACK);
                mPaint.setStrokeWidth(3);
            }
            canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
            // canvas.drawLine(0, x+10, 40, x+10, mPaint);
        }

        // Display the main field colors using LinearGradient
        for (int x = 0; x < 256; x++) {
            int[] colors = new int[2];
            colors[0] = mMainColors[x];
            colors[1] = Color.BLACK;
            Shader shader = new LinearGradient(0, 50, 0, 306, colors, null,
                    Shader.TileMode.REPEAT);
            mPaint.setShader(shader);
            canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
        }
        mPaint.setShader(null);

        // Display the circle around the currently selected color in the
        // main field
        if (mCurrentX != 0 && mCurrentY != 0) {
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(Color.BLACK);
            canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
        }

        // Draw a 'button' with the currently selected color
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mCurrentColor);
        canvas.drawRect(10, 316, 138, 356, mPaint);

        // Set the text color according to the brightness of the color
        if (Color.red(mCurrentColor) + Color.green(mCurrentColor)
                + Color.blue(mCurrentColor) < 384)
            mPaint.setColor(Color.WHITE);
        else
            mPaint.setColor(Color.BLACK);
        canvas.drawText(
                getResources()
                        .getString(R.string.settings_bg_color_confirm), 74,
                340, mPaint);

        // Draw a 'button' with the default color
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mDefaultColor);
        canvas.drawRect(138, 316, 266, 356, mPaint);

        // Set the text color according to the brightness of the color
        if (Color.red(mDefaultColor) + Color.green(mDefaultColor)
                + Color.blue(mDefaultColor) < 384)
            mPaint.setColor(Color.WHITE);
        else
            mPaint.setColor(Color.BLACK);
        canvas.drawText(
                getResources().getString(
                        R.string.settings_default_color_confirm), 202, 340,
                mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(276, 366);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_DOWN)
            return true;
        float x = event.getX();
        float y = event.getY();

        // If the touch event is located in the hue bar
        if (x > 10 && x < 266 && y > 0 && y < 40) {
            // Update the main field colors
            mCurrentHue = (255 - x) * 360 / 255;
            updateMainColors();

            // Update the current selected color
            int transX = mCurrentX - 10;
            int transY = mCurrentY - 60;
            int index = 256 * (transY - 1) + transX;
            if (index > 0 && index < mMainColors.length)
                mCurrentColor = mMainColors[256 * (transY - 1) + transX];

            // Force the redraw of the dialog
            invalidate();
        }

        // If the touch event is located in the main field
        if (x > 10 && x < 266 && y > 50 && y < 306) {
            mCurrentX = (int) x;
            mCurrentY = (int) y;
            int transX = mCurrentX - 10;
            int transY = mCurrentY - 60;
            int index = 256 * (transY - 1) + transX;
            if (index > 0 && index < mMainColors.length) {
                // Update the current color
                mCurrentColor = mMainColors[index];
                // Force the redraw of the dialog
                invalidate();
            }
        }

        // If the touch event is located in the left button, notify the
        // listener with the current color
        if (x > 10 && x < 138 && y > 316 && y < 356)
            mListener.colorChanged("", mCurrentColor);

        // If the touch event is located in the right button, notify the
        // listener with the default color
        if (x > 138 && x < 266 && y > 316 && y < 356)
            mListener.colorChanged("", mDefaultColor);

        return true;
    }
}

public ColorPickerDialog(Context context, OnColorChangedListener listener,
        String key, int initialColor, int defaultColor) {
    super(context);

    mListener = listener;
    mKey = key;
    mInitialColor = initialColor;
    mDefaultColor = defaultColor;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OnColorChangedListener l = new OnColorChangedListener() {
        public void colorChanged(String key, int color) {
            mListener.colorChanged(mKey, color);
            dismiss();
        }
    };

    setContentView(new ColorPickerView(getContext(), l, mInitialColor,
            mDefaultColor));
    setTitle(R.string.settings_bg_color_dialog);

    }
}
person Robo    schedule 05.10.2012
comment
@jRowan Могу я спросить, как вы инициализировали Dialog в своей деятельности? - person Menelaos Kotsollaris; 31.12.2014
comment
@Try_me34 в этой ссылке я объясняю это в редактировании stackoverflow .com/questions/22724899/ - person JRowan; 31.12.2014
comment
Какой ужасный код... Использование этого действительно причиняет боль. - person Firzen; 22.06.2015
comment
Если кто-то из будущего придет сюда, я создал один класс: github.com/carlosbar/AndroidColorPicker - person Carlos Barcellos; 02.12.2019

Я оказался здесь в поисках средства выбора цвета HSV, которое предлагало прозрачность и копирование/вставку шестнадцатеричного значения. Ни один из существующих ответов не соответствовал этим потребностям, поэтому вот библиотека, которую я написал:

Палитра цветов HSV-Alpha для Android (GitHub).

демонстрационная версия HSV-Alpha Color Picker (Google Play).

Я надеюсь, что это полезно для кого-то еще.

Диалоговое окно выбора цвета

person Martin Stone    schedule 28.07.2015
comment
Это отличная библиотека выбора цвета. - person Thracian; 16.03.2018

Мы только что загрузили палитру цветов AmbilWarna в Maven:

https://github.com/yukuku/ambilwarna

Его можно использовать либо как диалоговое окно, либо как запись предпочтений.

введите здесь описание изображения

person Denis Kniazhev    schedule 06.05.2015
comment
Без излишеств, прост в использовании. - person quilkin; 10.02.2021

Если вам нужно фрагментарное решение, я сделал ответвление android-color-picker, где DialogFragment используется и воссоздается при изменении конфигурации. Вот ссылка: https://github.com/lomza/android-color-picker

person lomza    schedule 30.09.2013

Вот еще одна библиотека:
https://github.com/eltos/SimpleDialogFragments

Особенности цветового круга и диалоговых окон выбора палитры

введите здесь описание изображения

введите здесь описание изображения

Использование для выбора цвета HSV:

Добавьте библиотеку из maven и в своем коде просто позвоните:

SimpleColorWheelDialog.build()
                      .color(0xFFCF4747) // optional initial color
                      .alpha(true)
                      .show(Activity.this, COLOR_PICKER);

и чтобы получить результаты, пусть Activity или фрагмент реализуют OnDialogResultListener:

@Override
public boolean onResult(@NonNull String dialogTag, int which, @NonNull Bundle extras) {
    if (COLOR_PICKER.equals(dialogTag) && which == BUTTON_POSITIVE){
        int color = extras.getInt(SimpleColorWheelDialog.COLOR);
        // ...
        return true;
    }
    return false;
}

person Philipp    schedule 04.03.2017

После некоторых поисков в ссылках на Android новичок QuadFlask Color Picker кажется технически и эстетически хорошим выбором. Также он имеет ползунок прозрачности и поддерживает цвета в шестнадцатеричном коде.

Взгляните:
Палитра цветов QuadFlask

person Shayan Amani    schedule 06.10.2015