draw Outline on Canvas - Android Graphics

Android examples for Graphics:Canvas

Description

draw Outline on Canvas

Demo Code


//package com.java2s;
import android.content.Context;
import android.graphics.Canvas;

import android.graphics.Paint;

import android.view.View;
import android.view.ViewGroup;

public class Main {
    private static final int VIEW_COLOR = 0xFF3366FF;
    private static final int CONTAINER_COLOR = 0xFF2AFF80;
    private static final float BORDER_WIDTH_DP = 2.5f;
    private static final float BORDER_SIZE_RATIO = 0.2f;
    private static final float MAX_BORDER_SIZE_DP = 15;

    public static void drawOutline(Context context, View view, Canvas canvas) {
        int width = view.getWidth();
        int height = view.getHeight();
        final int color;
        if (view instanceof ViewGroup) {
            color = CONTAINER_COLOR;/*from www  . ja  va 2  s  .  c  o m*/
        } else {
            color = VIEW_COLOR;
        }

        final float density = context.getResources().getDisplayMetrics().density;
        float borderWidth = BORDER_WIDTH_DP * density;
        float maxBorderSize = MAX_BORDER_SIZE_DP * density;

        Paint borderPaint = new Paint();
        borderPaint.setStrokeWidth(borderWidth);
        borderPaint.setColor(color);

        final float lineWidth = Math.min(maxBorderSize, width
                * BORDER_SIZE_RATIO);
        final float lineHeight = Math.min(maxBorderSize, height
                * BORDER_SIZE_RATIO);

        canvas.drawLine(0, 0, lineWidth, 0, borderPaint);
        canvas.drawLine(0, 0, 0, lineHeight, borderPaint);

        canvas.drawLine(0, height, 0, height - lineHeight, borderPaint);
        canvas.drawLine(0, height, lineWidth, height, borderPaint);

        canvas.drawLine(width, 0, width, lineHeight, borderPaint);
        canvas.drawLine(width, 0, width - lineWidth, 0, borderPaint);

        canvas.drawLine(width, height, width, height - lineHeight,
                borderPaint);
        canvas.drawLine(width, height, width - lineWidth, height,
                borderPaint);
    }
}

Related Tutorials