Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2012 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.
 */

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Color;

import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;

public class Main {
    /**
     * Frames the input bitmap in a circle.
     */
    public static Bitmap frameBitmapInCircle(Bitmap input) {
        if (input == null) {
            return null;
        }

        // Crop the image if not squared.
        int inputWidth = input.getWidth();
        int inputHeight = input.getHeight();
        int targetX, targetY, targetSize;
        if (inputWidth >= inputHeight) {
            targetX = inputWidth / 2 - inputHeight / 2;
            targetY = 0;
            targetSize = inputHeight;
        } else {
            targetX = 0;
            targetY = inputHeight / 2 - inputWidth / 2;
            targetSize = inputWidth;
        }

        // Create an output bitmap and a canvas to draw on it.
        Bitmap output = Bitmap.createBitmap(targetSize, targetSize, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        // Create a black paint to draw the mask.
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);

        // Draw a circle.
        canvas.drawCircle(targetSize / 2, targetSize / 2, targetSize / 2, paint);

        // Replace the black parts of the mask with the input image.
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(input, targetX /* left */, targetY /* top */, paint);

        return output;
    }
}