Utilidades de cor

Este artigo irá ajudá-lo a instalar, importar e usar utils de cores. Saiba como usar utils de cores para aplicar temas e paletas nos pontos de dados de um visual do Power BI.

Pré-requisitos

Para usar o pacote, instale:

Instalação

Para instalar o pacote, você deve executar o seguinte comando no diretório com seu visual atual:

npm install powerbi-visuals-utils-colorutils --save

Este comando instala o pacote e adiciona um pacote como uma dependência ao seu package.json arquivo.

Utilização

Para usar utils de interatividade, você precisa importar o componente necessário no código-fonte do visual.

import { ColorHelper } from "powerbi-visuals-utils-colorutils";

Saiba como instalar e usar o colorUtils em seus visuais do Power BI:

  • [Guia de Utilização] O Guia de Uso descreve uma API pública do pacote. Ele fornece uma descrição e exemplos para cada interface pública.

Este pacote contém as seguintes classes e módulos:

Ajudante de Cores

A ColorHelper classe fornece as seguintes funções e métodos:

getColorForSeriesValue

Este método obtém a cor para um valor de série específico. Se nenhuma cor explícita ou cor padrão tiver sido definida, a cor será alocada a partir da escala de cores para esta série.

getColorForSeriesValue(objects: IDataViewObjects, value: PrimitiveValue, themeColorName?: ThemeColorName): string;

Exemplo de getColorForSeriesValue

import powerbi from "powerbi-visuals-api";
import { ColorHelper } from "powerbi-visuals-utils-colorutils";

import DataViewObjects = powerbi.DataViewObjects;

import DataViewValueColumns = powerbi.DataViewValueColumns;
import DataViewValueColumnGroup = powerbi.DataViewValueColumnGroup;
import DataViewObjectPropertyIdentifier = powerbi.DataViewObjectPropertyIdentifier;

import IVisual = powerbi.extensibility.visual.IVisual;
import IColorPalette = powerbi.extensibility.IColorPalette;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;

export class YourVisual implements IVisual {
    // Implementation of IVisual

    private colorPalette: IColorPalette;

    constructor(options: VisualConstructorOptions) {
        this.colorPalette = options.host.colorPalette;
    }

    public update(visualUpdateOptions: VisualUpdateOptions): void {
        const valueColumns: DataViewValueColumns = visualUpdateOptions.dataViews[0].categorical.values,
            grouped: DataViewValueColumnGroup[] = valueColumns.grouped(),
            defaultDataPointColor: string = "green",
            fillProp: DataViewObjectPropertyIdentifier = {
                objectName: "objectName",
                propertyName: "propertyName"
            };

        let colorHelper: ColorHelper = new ColorHelper(
            this.colorPalette,
            fillProp,
            defaultDataPointColor);

        for (let i = 0; i < grouped.length; i++) {
            let grouping: DataViewValueColumnGroup = grouped[i];

            let color = colorHelper.getColorForSeriesValue(grouping.objects, grouping.name); // returns a color of the series
        }
    }
}

getColorForMeasure

Este método obtém a cor para uma medida específica.

 getColorForMeasure(objects: IDataViewObjects, measureKey: any, themeColorName?: ThemeColorName): string;

Obter cor para exemplo de medida

import powerbi from "powerbi-visuals-api";
import { ColorHelper } from "powerbi-visuals-utils-colorutils";

import DataViewObjects = powerbi.DataViewObjects;
import IVisual = powerbi.extensibility.visual.IVisual;
import IColorPalette = powerbi.extensibility.IColorPalette;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import DataViewObjectPropertyIdentifier = powerbi.DataViewObjectPropertyIdentifier;
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;

export class YourVisual implements IVisual {
    // Implementation of IVisual

    private colorPalette: IColorPalette;

    constructor(options: VisualConstructorOptions) {
        this.colorPalette = options.host.colorPalette;
    }

    public update(visualUpdateOptions: VisualUpdateOptions): void {
        const objects: DataViewObjects = visualUpdateOptions.dataViews[0].categorical.categories[0].objects[0],
            defaultDataPointColor: string = "green",
            fillProp: DataViewObjectPropertyIdentifier = {
                objectName: "objectName",
                propertyName: "propertyName"
            };

        let colorHelper: ColorHelper = new ColorHelper(
            this.colorPalette,
            fillProp,
            defaultDataPointColor);

        let color = colorHelper.getColorForMeasure(objects, ""); // returns a color
    }
}

estática normalizeSelector

Esse método retorna o seletor normalizado.

static normalizeSelector(selector: Selector, isSingleSeries?: boolean): Selector;

exemplo de static normalizeSelector

import ISelectionId = powerbi.visuals.ISelectionId;
import { ColorHelper } from "powerbi-visuals-utils-colorutils";

let selectionId: ISelectionId = ...;
let selector = ColorHelper.normalizeSelector(selectionId.getSelector(), false);

Métodos getThemeColor e getHighContrastColor ambos estão relacionados com cores de tema de cores. ColorHelper tem a isHighContrast propriedade.

getThemeColor

Esse método retorna a cor do tema.

 getThemeColor(themeColorName?: ThemeColorName): string;

getHighContrastColor

Esse método retorna a cor para o modo de alto contraste.

getHighContrastColor(themeColorName?: ThemeColorName, defaultColor?: string): string;

Exemplo de modo de alto contraste


import { ColorHelper } from "powerbi-visuals-utils-colorutils";

export class MyVisual implements IVisual {
        private colorHelper: ColorHelper;

        private init(options: VisualConstructorOptions): void {
            this.colors = options.host.colorPalette;
            this.colorHelper = new ColorHelper(this.colors);
        } 

            private createViewport(element: HTMLElement): void {
                const fontColor: string = "#131aea";
                const axisBackgroundColor: string = this.colorHelper.getThemeColor();
                
                // some d3 code before
                d3ElementName.attr("fill", colorHelper.getHighContrastColor("foreground", fontColor);
            }
                
            public static parseSettings(dataView: DataView, colorHelper: ColorHelper): VisualSettings {
                // some code that should be applied on formatting settings
                if (colorHelper.isHighContrast) {
                        this.settings.fontColor = colorHelper.getHighContrastColor("foreground", this.settings.fontColor);
                    }
            }
}

ColorUtils

O módulo fornece as seguintes funções:

hexToRGBString

Converte uma cor hexadecimal em uma cadeia de caracteres RGB.

function hexToRGBString(hex: string, transparency?: number): string

Exemplo de hexToRGBString

import  { hexToRGBString } from "powerbi-visuals-utils-colorutils";

hexToRGBString('#112233');

// returns: "rgb(17,34,51)"

girar

Gira a cor RGB.

function rotate(rgbString: string, rotateFactor: number): string

Exemplo de rotação

import { rotate } from "powerbi-visuals-utils-colorutils";

rotate("#CC0000", 0.25); // returns: #66CC00

parseColorString

Analisa qualquer cadeia de caracteres de cor para o formato RGB.

function parseColorString(color: string): RgbColor

exemplo de parseColorString

import { parseColorString } from "powerbi-visuals-utils-colorutils";

parseColorString('#09f');
// returns: {R: 0, G: 153, B: 255 }

parseColorString('rgba(1, 2, 3, 1.0)');
// returns: {R: 1, G: 2, B: 3, A: 1.0 }

calcularHighlightColor

Calcula a cor de realce do rgbColor com base no lumianceThreshold e no delta.

function calculateHighlightColor(rgbColor: RgbColor, lumianceThreshold: number, delta: number): string

exemplo de calculateHighlightColor

import { calculateHighlightColor } from "powerbi-visuals-utils-colorutils";

let yellow = "#FFFF00",
    yellowRGB = parseColorString(yellow);

calculateHighlightColor(yellowRGB, 0.8, 0.2);

// returns: '#CCCC00'

createLinearColorScale

Retorna uma escala de cores linear para um domínio específico de números.

function createLinearColorScale(domain: number[], range: string[], clamp: boolean): LinearColorScale

Exemplo de createLinearColorScale

import { createLinearColorScale } from "powerbi-visuals-utils-colorutils";

let scale = ColorUtility.createLinearColorScale(
    [0, 1, 2, 3, 4],
    ["red", "green", "blue", "black", "yellow"],
    true);

scale(1); // returns: green
scale(10); // returns: yellow

shadeColor

Converte uma expressão hexadecimal de cadeia de caracteres em um número e calcula a porcentagem e os canais R, G e B. Aplica a porcentagem para cada canal e retorna o valor hexadecimal como uma cadeia de caracteres com um sinal de libra.

function shadeColor(color: string, percent: number): string

exemplo de shadeColor

import { shadeColor } from "powerbi-visuals-utils-colorutils";

shadeColor('#000000', 0.1); // returns '#1a1a1a'
shadeColor('#FFFFFF', -0.5); // returns '#808080'
shadeColor('#00B8AA', -0.25); // returns '#008a80'
shadeColor('#00B8AA', 0); // returns '#00b8aa'

rgbBlend

Sobrepõe uma cor com opacidade sobre uma cor de fundo. Qualquer canal alfa é ignorado.

function rgbBlend(foreColor: RgbColor, opacity: number, backColor: RgbColor): RgbColor

Exemplo de rgbBlend

import { rgbBlend} from "powerbi-visuals-utils-colorutils";

rgbBlend({R: 100, G: 100, B: 100}, 0.5, {R: 200, G: 200, B: 200});

// returns: {R: 150, G: 150, B: 150}

canalBlend

Combina um único canal para duas cores.

function channelBlend(foreChannel: number, opacity: number, backChannel: number): number

exemplo de channelBlend

import { channelBlend} from "powerbi-visuals-utils-colorutils";

channelBlend(0, 1, 255); // returns: 0
channelBlend(128, 1, 255); // returns: 128
channelBlend(255, 0, 0); // returns: 0
channelBlend(88, 0, 88); // returns: 88

hexBlend [en]

Sobrepõe uma cor com opacidade sobre uma cor de fundo.

function hexBlend(foreColor: string, opacity: number, backColor: string): string

Exemplo de hexBlend

import { hexBlend} from "powerbi-visuals-utils-colorutils";

let yellow = "#FFFF00",
    black = "#000000",
    white = "#FFFFFF";

hexBlend(yellow, 0.5, white); // returns: "#FFFF80"
hexBlend(white, 0.5, yellow); // returns: "#FFFF80"

hexBlend(yellow, 0.5, black); // returns: "#808000"
hexBlend(black, 0.5, yellow); // returns: "#808000"