Function palette::serde::deserialize_with_optional_pre_alpha

source ยท
pub fn deserialize_with_optional_pre_alpha<'de, T, D>(
    deserializer: D,
) -> Result<PreAlpha<T>, D::Error>
where T: Premultiply + Deserialize<'de>, T::Scalar: Stimulus + Deserialize<'de>, D: Deserializer<'de>,
Expand description

Deserialize a premultiplied transparent color without requiring the alpha to be specified.

A color with missing alpha will be interpreted as fully opaque.

use serde::Deserialize;
use palette::{LinSrgba, LinSrgb, blend::PreAlpha};

type PreRgba = PreAlpha<LinSrgb<f32>>;

#[derive(Deserialize, PartialEq, Debug)]
struct MyColors {
    #[serde(deserialize_with = "palette::serde::deserialize_with_optional_pre_alpha")]
    opaque: PreRgba,
    #[serde(deserialize_with = "palette::serde::deserialize_with_optional_pre_alpha")]
    transparent: PreRgba,
}

let my_colors = MyColors {
    opaque: LinSrgba::new(0.6, 0.8, 0.3, 1.0).into(),
    transparent: LinSrgba::new(0.6, 0.8, 0.3, 0.5).into(),
};

let json = r#"{
    "opaque":{"red":0.6,"green":0.8,"blue":0.3},
    "transparent":{"red":0.3,"green":0.4,"blue":0.15,"alpha":0.5}
}"#;
assert_eq!(
    serde_json::from_str::<MyColors>(json).unwrap(),
    my_colors
);