1

我有一个 android 应用程序,它使用 android.support.v7.graphics.Palette 从动态图像中获取颜色信息,然后自定义活动的布局以使用图像中的变异颜色。我的问题是,Angular 5 有类似的东西吗?我想对该项目的 Web 版本进行建模,使其尽可能接近 android 版本。这意味着在选择图像后动态设置一些样式颜色。

更新:我一直在寻找 JavaScript 的ColorThief()。但我不确定如何从 Angular 5 组件访问它。

谢谢PK

4

1 回答 1

8

对于任何寻找这样的东西的人,我最终使用了node-vibrant.js。我运行 npm install 然后将文件添加到 angular.json 文件中的脚本数组

"scripts": [
  "node_modules/node-vibrant/dist/vibrant.min.js"
]

然后我将 tsconfig.json 文件更改为以下内容:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "commonjs",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "allowJs": true
}

然后我将 Vibrant 和 Palette 导入到我的 Angular 6.0.0 组件中

import Vibrant from 'node-vibrant';
import { Palette } from 'node-vibrant/lib/color';

然后很容易用图像的 url 调用 ngOnInit()

getVibrantColor(url: string){
  // Using builder
  Vibrant.from(url).getPalette((err, palette) => {
    console.log(palette)
    this.palette = palette;
  });

}

styleContainer(): any {
  console.log('palette', this.palette);
  if (this.palette.LightVibrant) {
    return { 'background-color': this.palette.LightVibrant.getHex(), 'border-color': 
      this.palette.LightMuted.getHex(), 'color': '#000000' };
  } else {
    return { 'background-color': '#FFFFFF', 'border-color':        
       this.palette.LightMuted.getHex(), 'color': '#000000' };
  }

}

并从 html 文件中调用它:

<div *ngIf="palette" class="col-lg-8 details-top-container" 
[ngStyle]="styleContainer()"></div>

最困难的部分是获得正确的导入声明。

import * as Vibrant from 'node-vibrant';

不会像文档所说的那样工作。

希望这可以节省一些时间。

PK

于 2018-07-05T12:45:41.603 回答