【问题标题】:How to convert HSL color to other like RGB, Hex?如何将 HSL 颜色转换为 RGB、Hex 等其他颜色?
【发布时间】:2018-10-28 11:10:03
【问题描述】:

我正在开发颜色转换器应用程序,其中一个在 EditText 中输入色相、饱和度和亮度值。单击转换按钮时,HSL 值将转换为 RGB 和 Hex。然后将这些值设置为 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();
                }

            }
        });
    }
}

【问题讨论】:

  • 从 HSL 转换为 RGB 颜色值已经在很多 Stackoverflow 帖子中介绍过,例如,this one
  • 它是 HSV 我需要转换 HSL

标签: android


【解决方案1】:

使用下面的方法

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

【讨论】:

  • 不兼容类型:必需:android.graphics.Color fount:int
  • 将变量类型从 Color 更改为 int
  • 感谢两位。将变量类型从 Color 更改为 int 已解决问题
  • 我测试没问题,请在这里写输入
  • @YasharPanahi 无法解析方法 'HSLToColor(float[])'
【解决方案2】:

来源链接: 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();
            }

        }
    });

【讨论】:

    【解决方案3】:

    从一个问题的答案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();
                }
    
                }
            });
    

    【讨论】:

    • 输入: hsl(205, 63, 52) 输出: RGB:832575, 832575, 832575 十六进制:#cb43fcb43fcb43f
    • hsl 输入应在 [0,1] 范围内。
    • 我是 android 新手,请在您的回答中使用和编辑我的代码
    • 我已经尝试过您现在更新答案的方式
    • 你说 HSL 输入应该在 [0,1] 范围内,但是 HSL 值可以是 Hue[0-360]、Saturation[0-100]、Lightness[0-100]
    猜你喜欢
    • 2011-02-04
    • 2019-02-08
    • 2022-11-25
    • 2018-06-16
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2011-04-17
    相关资源
    最近更新 更多