1/*
2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import Log from './log';
17
18const TAG = 'CommonUtils';
19
20class CommonUtil {
21  public setColorOpacity(color: string, opacity: number): string {
22    try {
23      let r;
24      let g;
25      let b;
26      if (color[0] === '#') {
27        color = color.slice(1);
28      }
29      const RGBA_LENGTH = 8;
30      if (color.length === RGBA_LENGTH) {
31        const RGB_IN_RGBA_BEGIN = 2;
32        const RGB_IN_RGBA_END = 8;
33        color = color.slice(RGB_IN_RGBA_BEGIN, RGB_IN_RGBA_END);
34      }
35      const BASE_16 = 16;
36      const MAX_UINT8 = 255;
37      const BIT_8 = 8;
38      r = (parseInt(color, BASE_16) >> BIT_8 >> BIT_8) & MAX_UINT8;
39      g = (parseInt(color, BASE_16) >> BIT_8) & MAX_UINT8;
40      b = parseInt(color, BASE_16) & MAX_UINT8;
41      let a = opacity;
42      let colorTransparency = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
43      return colorTransparency;
44    } catch (error) {
45      Log.error(TAG, `setColorOpacity failed, error code: ${error.code}, message: ${error.message}.`);
46    }
47    return '';
48  }
49
50  public getColor(context: Context, resColor: Resource): string {
51    try {
52      const BASE_16 = 16;
53      let color: string = context.resourceManager.getColorSync(resColor.id).toString(BASE_16);
54      Log.info(TAG, `color : ${color}`);
55      return color;
56    } catch (error) {
57      Log.error(TAG, `getColor failed, error Code:${error.code}, message: ${error.message}.`);
58    }
59    return '';
60  }
61}
62
63let commonUtil = new CommonUtil();
64export default commonUtil;