Composite two potentially translucent colors over each other and returns the result. - Android Graphics

Android examples for Graphics:Color

Description

Composite two potentially translucent colors over each other and returns the result.

Demo Code

/*//w  ww.j  a v a2  s .  co  m
 * Copyright 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import android.graphics.Color;

public class Main {
    /**
     * Composite two potentially translucent colors over each other and returns the result.
     */
    public static int compositeColors(int foreground, int background) {
        final float alpha1 = Color.alpha(foreground) / 255f;
        final float alpha2 = Color.alpha(background) / 255f;

        float a = (alpha1 + alpha2) * (1f - alpha1);
        float r = (Color.red(foreground) * alpha1)
                + (Color.red(background) * alpha2 * (1f - alpha1));
        float g = (Color.green(foreground) * alpha1)
                + (Color.green(background) * alpha2 * (1f - alpha1));
        float b = (Color.blue(foreground) * alpha1)
                + (Color.blue(background) * alpha2 * (1f - alpha1));

        return Color.argb((int) a, (int) r, (int) g, (int) b);
    }
}

Related Tutorials