user10570128
user10570128

Reputation:

How to convert HSL color to other like RGB, Hex?

I'm developing color converter app in which one enters Hue, Saturation and Lightness values in EditText. When convert button is clicked the HSL value is converted to RGB and Hex. Then these values are set to TextViews. My question is how to convert HSL color value to other colors like HEX, RGB etc.

Here is my code: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/backgroundLin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/hueEt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="000"
            android:inputType="numberDecimal"
            android:maxLength="6"
            android:padding="5dp"
            android:textAlignment="center" />

        <EditText
            android:id="@+id/satEt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="000"
            android:inputType="numberDecimal"
            android:maxLength="6"
            android:padding="5dp"
            android:textAlignment="center" />

        <EditText
            android:id="@+id/ligEt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="000"
            android:inputType="numberDecimal"
            android:maxLength="6"
            android:padding="5dp"
            android:textAlignment="center" />
    </LinearLayout>

    <Button
        android:id="@+id/convertBtn"
        style="@style/Base.Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:drawablePadding="10dp"
        android:text="Convert"
        android:textSize="18sp" />

    <View
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/rgbTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/hexTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java

package com.blogspot.atifsoftwares.myapplication;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText mHueEt, mSaturationEt, mLightnessEt;
    TextView mRgbTv, mHexTv;
    View mPreviewView;
    Button mConvertBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHueEt = findViewById(R.id.hueEt);
        mSaturationEt = findViewById(R.id.satEt);
        mLightnessEt = findViewById(R.id.ligEt);
        mConvertBtn = findViewById(R.id.convertBtn);
        mRgbTv = findViewById(R.id.rgbTv);
        mHexTv = findViewById(R.id.hexTv);
        mPreviewView = findViewById(R.id.previewView);

        mConvertBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float hue = Float.parseFloat(mHueEt.getText().toString().trim());
                float saturation = Float.parseFloat(mSaturationEt.getText().toString().trim());
                float lightness = Float.parseFloat(mLightnessEt.getText().toString().trim());

                //HSL
                int color = Color.HSVToColor(new float[]{hue, saturation, lightness});
                //RGB
                int red = Color.red(color);
                int green = Color.green(color);
                int blue = Color.blue(color);
                int alpha = Color.alpha(color);
                //Hex
                String hex = String.format("#%02x%02x%02x", red, green, blue);

                try {
                    mHexTv.setText("Hex: " + hex);
                    mRgbTv.setText("RGB: " + red + ", " + green + ", " + blue);
                    mPreviewView.setBackgroundColor(color);
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}

Upvotes: 0

Views: 4812

Answers (3)

AtifSayings
AtifSayings

Reputation: 854

Source Link: https://developer.android.com/reference/android/support/v4/graphics/ColorUtils

import this class:

import static android.support.v4.graphics.ColorUtils.HSLToColor;

Change your onClick code as below:

mConvertBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            float hue = Float.parseFloat(mHueEt.getText().toString().trim());
            float saturation = Float.parseFloat(mSaturationEt.getText().toString().trim());
            float lightness = Float.parseFloat(mLightnessEt.getText().toString().trim());

            //store H,S,L values in float array
            float[] color = {hue, saturation/100, lightness/100};
            //convert hsl values to int color
            int intColor = HSLToColor(color);
            //RGB
            int red = Color.red(intColor);
            int green = Color.green(intColor);
            int blue = Color.blue(intColor);
            int alpha = Color.alpha(intColor);
            //Hex
            String hex = String.format("#%02x%02x%02x", red, green, blue);

            try {
                mHexTv.setText("Hex: " + hex);
                mRgbTv.setText("RGB: " + red + ", " + green + ", " + blue);
                mPreviewView.setBackgroundColor(intColor);
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

        }
    });

Upvotes: 1

karan
karan

Reputation: 8853

From one of the answer to a question here. you use the below function to convert your HSL color to RGB color.

Note that all integer are declared as float (i.e 1f) and must be float, else you will optain grey colors.
HSL to RGB

 /**
 * Converts an HSL color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes h, s, and l are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param h       The hue
 * @param s       The saturation
 * @param l       The lightness
 * @return int array, the RGB representation
 */
public static int[] hslToRgb(float h, float s, float l){
    float r, g, b;

    if (s == 0f) {
        r = g = b = l; // achromatic
    } else {
        float q = l < 0.5f ? l * (1 + s) : l + s - l * s;
        float p = 2 * l - q;
        r = hueToRgb(p, q, h + 1f/3f);
        g = hueToRgb(p, q, h);
        b = hueToRgb(p, q, h - 1f/3f);
    }
    int[] rgb = {(int) (r * 255), (int) (g * 255), (int) (b * 255)};
    return rgb;
}

/** Helper method that converts hue to rgb */
public static float hueToRgb(float p, float q, float t) {
    if (t < 0f)
        t += 1f;
    if (t > 1f)
        t -= 1f;
    if (t < 1f/6f)
        return p + (q - p) * 6f * t;
    if (t < 1f/2f)
        return q;
    if (t < 2f/3f)
        return p + (q - p) * (2f/3f - t) * 6f;
    return p;
}

Change your onClick code as below

mConvertBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float hue = Float.parseFloat(mHueEt.getText().toString().trim());
                float saturation = Float.parseFloat(mSaturationEt.getText().toString().trim());
                float lightness = Float.parseFloat(mLightnessEt.getText().toString().trim());

                //HSL
                int anscolor[] = hslToRgb(hue, saturation, lightness);
                //RGB
                int red = anscolor[0];
                int green = anscolor[1];
                int blue = anscolor[2];

                String hex = String.format("#%02x%02x%02x", red, green, blue);

            try {
                mHexTv.setText("Hex: " + hex);
                mRgbTv.setText("RGB: " + red + ", " + green + ", " + blue);
                mPreviewView.setBackgroundColor(color);
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            }
        });

Upvotes: 0

Yashar Panahi
Yashar Panahi

Reputation: 3514

Use below method

Color color = Color.HSVToColor( new float[]{ hue, saturation , lightness } ) );

and for convert color to rgb use

int red = Color.red(color );
int green = Color.green(color );
int blue = Color.blue(color );
int alpha = Color.alpha(color );

Upvotes: 4

Related Questions