如何将HSL颜色转换为RGB,Hex等其他颜色?

时间:2018-10-28 11:10:03

标签: android

我正在开发颜色转换器应用程序,其中一个应用程序在EditText中输入色相,饱和度和亮度值。单击转换按钮时,HSL值将转换为RGB和十六进制。然后将这些值设置为TextViews。 我的问题是如何将HSL颜色值转换为HEX,RGB等其他颜色。

这是我的代码: 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();
                }

            }
        });
    }
}

3 个答案:

答案 0 :(得分:3)

使用以下方法

Color 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 );

答案 1 :(得分:0)

从答案之一到问题here。您可以使用以下功能将HSL颜色转换为RGB颜色。

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;
}

如下更改您的onClick代码

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();
            }

            }
        });

答案 2 :(得分:0)

源链接: https://developer.android.com/reference/android/support/v4/graphics/ColorUtils

导入此类:

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

如下更改您的onClick代码:

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();
            }

        }
    });