Adjust Alpha Channel

Description

Allows to set, adjust, or remove transparency (alpha channel). In case alpha is a single float, a constant transparency will be added to all colors. If alpha is a list or numpy.ndarray it must be the same length as the number of colors in the object x and all values must be convertable to float/int in the range of [0., 1.]. Allows to add individual transparency for each color in x.

Usage

adjust_transparency(x, alpha)

Arguments

x
sequence of colors; an object which inherits from colorsspace.colorlib.colorobject.
alphaNone, float, int, list, numpy.ndarray
None will remove existing transparency (if existing). If float, list, or numpy.ndarray` trnasparency will be added. See function description for more details.

Return

numpy.ndarray or None: None if the colorobject has no defined transparency, else a numpy.ndarray is returned.

Examples

from colorspace import *
from colorspace.colorlib import hexcols
import numpy as np
# Three colors without transparency
cols1 = ['#023FA5',   '#E2E2E2',   '#8E063B']
# Same colors as in `cols1` with transparency of 80%, 40%, 80%
cols2 = ['#023FA5CC', '#E2E2E266', '#8E063BCC']

# Converting list of hex colors `cols1` into `hexcolor` objects
x1 = hexcols(cols1)
x1
  • #023FA5
  • #E2E2E2
  • #8E063B
# Extract transparency
extract_transparency(x1) # Returns 'None' (no transparency)
# `x1`: Setting constant transparency of 0.5 for all colors
adjust_transparency(x1, 0.5)
  • #023FA580
  • #E2E2E280
  • #8E063B80
# Setting custom transparency (adjusting; overwrite existing 0.5)
adjust_transparency(x1, [0.7, 0.3, 0.7]) # Add transparency
  • #023FA5B3
  • #E2E2E24D
  • #8E063BB3
# Converting list of hex colors `cols2` into `hexcolor` objects
# and extract transparency defined via 8 digit hex color str
x2 = hexcols(cols2)
extract_transparency(x2)
array([0.8, 0.4, 0.8])
# Removing transparency, extracting new values (None)
x2 = adjust_transparency(x2, None)
extract_transparency(x2) # Returns 'None' (no transparency)
# Adding transparency again
x2 = adjust_transparency(x2, np.asarray([0.8, 0.4, 0.8]))
x2
  • #023FA5CC
  • #E2E2E266
  • #8E063BCC
extract_transparency(x2)
array([0.8, 0.4, 0.8])

Raises

  • TypeError: If input object does not inherit from colorspace.colorlib.colorobject.
  • TypeError: If alpha is not one of the expected types.
  • ValueError: If alpha is list or numpy.ndarray and does not match length of colors in x.
  • ValueError: If alpha cannot be converted to float.
  • ValueError: If alpha is outside of range [0., 1.].