Example usage for android.graphics Rect Rect

List of usage examples for android.graphics Rect Rect

Introduction

In this page you can find the example usage for android.graphics Rect Rect.

Prototype

public Rect() 

Source Link

Document

Create a new empty Rect.

Usage

From source file:Main.java

/**
 * The most useful answer about text drawing ever. http://stackoverflow.com/a/32081250
 *//*from  ww w .  jav  a2 s .c om*/
@Nullable
public static Bitmap createTypefaceBitmap(final Context context, @NonNull final String text, final int color,
        final float textSizePx) {
    final Typeface robotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf");

    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setSubpixelText(true);
    paint.setTypeface(robotoMedium);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(color);
    paint.setTextSize(textSizePx);

    final Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    Bitmap bitmap = null;
    if (!bounds.isEmpty()) {
        final int width = bounds.width();
        final int height = bounds.height();

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        final float x = bounds.left;
        final float y = height - bounds.bottom;

        final Canvas canvas = new Canvas(bitmap);
        canvas.drawText(text, x, y, paint);
    }

    return bitmap;
}

From source file:Main.java

public static Bitmap getColorPreviewBitmap(final Context context, final int color, final boolean border) {
    if (context == null)
        return null;
    final float density = context.getResources().getDisplayMetrics().density;
    final int width = (int) (32 * density), height = (int) (32 * density);

    final Bitmap bm = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    final Canvas canvas = new Canvas(bm);

    final int rectangleSize = (int) (density * 5);
    final int numRectanglesHorizontal = (int) Math.ceil(width / rectangleSize);
    final int numRectanglesVertical = (int) Math.ceil(height / rectangleSize);
    final Rect r = new Rect();
    boolean verticalStartWhite = true;
    for (int i = 0; i <= numRectanglesVertical; i++) {

        boolean isWhite = verticalStartWhite;
        for (int j = 0; j <= numRectanglesHorizontal; j++) {

            r.top = i * rectangleSize;// w  w w  .  jav a 2 s .  c  om
            r.left = j * rectangleSize;
            r.bottom = r.top + rectangleSize;
            r.right = r.left + rectangleSize;
            final Paint paint = new Paint();
            paint.setColor(isWhite ? Color.WHITE : Color.GRAY);

            canvas.drawRect(r, paint);

            isWhite = !isWhite;
        }

        verticalStartWhite = !verticalStartWhite;

    }
    canvas.drawColor(color);
    if (border) {
        final Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(1f * density);
        final float[] points = new float[] { 0, 0, width, 0, 0, 0, 0, height, width, 0, width, height, 0,
                height, width, height };
        canvas.drawLines(points, paint);
    }
    return bm;
}

From source file:Main.java

public static Bitmap getColorPreviewBitmap(final Context context, final int color, final boolean border) {
    if (context == null)
        return null;
    final float density = context.getResources().getDisplayMetrics().density;
    final int width = (int) (32 * density), height = (int) (32 * density);

    final Bitmap bm = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    final Canvas canvas = new Canvas(bm);

    final int rectrangleSize = (int) (density * 5);
    final int numRectanglesHorizontal = (int) Math.ceil(width / rectrangleSize);
    final int numRectanglesVertical = (int) Math.ceil(height / rectrangleSize);
    final Rect r = new Rect();
    boolean verticalStartWhite = true;
    for (int i = 0; i <= numRectanglesVertical; i++) {

        boolean isWhite = verticalStartWhite;
        for (int j = 0; j <= numRectanglesHorizontal; j++) {

            r.top = i * rectrangleSize;//from w ww.  j  a va  2s  .  c  o  m
            r.left = j * rectrangleSize;
            r.bottom = r.top + rectrangleSize;
            r.right = r.left + rectrangleSize;
            final Paint paint = new Paint();
            paint.setColor(isWhite ? Color.WHITE : Color.GRAY);

            canvas.drawRect(r, paint);

            isWhite = !isWhite;
        }

        verticalStartWhite = !verticalStartWhite;

    }
    canvas.drawColor(color);
    if (border) {
        final Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(1f * density);
        final float[] points = new float[] { 0, 0, width, 0, 0, 0, 0, height, width, 0, width, height, 0,
                height, width, height };
        canvas.drawLines(points, paint);
    }
    return bm;
}

From source file:cl.monsoon.s1next.binding.TextViewBindingAdapter.java

@BindingAdapter("increaseClickingArea")
public static void increaseClickingArea(TextView textView, float size) {
    // fork from http://stackoverflow.com/a/1343796
    View parent = (View) textView.getParent();
    // post in the parent's message queue to make sure the parent
    // lays out its children before we call View#getHitRect()
    parent.post(() -> {//from   ww w .  j  av  a  2 s . c  om
        final int halfSize = (int) (size / 2 + 0.5);
        Rect rect = new Rect();
        textView.getHitRect(rect);
        rect.top -= halfSize;
        rect.right += halfSize;
        rect.bottom += halfSize;
        rect.left -= halfSize;
        // use TouchDelegate to increase count's clicking area
        parent.setTouchDelegate(new TouchDelegate(rect, textView));
    });
}

From source file:Main.java

/**
 * convenience method to calculate the y offset for aligning
 * text vertically in its containing Sprite
 *
 * @param {int} yPos y-coordinate of the Sprite / "container" holding the text
 * @param {int} spriteHeight height of the Sprite / "container" holding the text
 * @param {String} text to render// ww  w .  j  a  v  a 2  s .  c  om
 * @param {Paint} textPaint the Paint used to render the text
 *
 * @return {int} the y coordinate for drawing the text
 */
public static int alignTextVertically(int yPos, int spriteHeight, String text, Paint textPaint) {
    final Rect bounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), bounds);

    return yPos + (spriteHeight / 2) + (bounds.height() / 2);
}

From source file:Main.java

/**
 * Create round, coloured bitmap with text embedded.
 * @param circleColor The color to use.//  w  w w .ja v a2 s .  c  o  m
 * @param diameterDP The diameter of the circle.
 * @param text The text to embed.
 * @return Bitmap showing a text.
 */
public static Bitmap generateCircleBitmap(int circleColor, float diameterDP, String text) {
    /**
     *
     * http://stackoverflow.com/questions/31168636/rounded-quickcontactbadge-with-text
     */
    final int textColor = 0xffffffff;

    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float diameterPixels = diameterDP * (metrics.densityDpi / 160f);
    float radiusPixels = diameterPixels / 2;

    // Create the bitmap
    Bitmap output = Bitmap.createBitmap((int) diameterPixels, (int) diameterPixels, Bitmap.Config.ARGB_8888);

    // Create the canvas to draw on
    Canvas canvas = new Canvas(output);
    canvas.drawARGB(0, 0, 0, 0);

    // Draw the circle
    final Paint paintC = new Paint();
    paintC.setAntiAlias(true);
    paintC.setColor(circleColor);
    canvas.drawCircle(radiusPixels, radiusPixels, radiusPixels, paintC);

    // Draw the text
    if (text != null && text.length() > 0) {
        final Paint paintT = new Paint();
        paintT.setColor(textColor);
        paintT.setAntiAlias(true);
        paintT.setTextSize(radiusPixels * 2);
        paintT.setTypeface(Typeface.SANS_SERIF);
        final Rect textBounds = new Rect();
        paintT.getTextBounds(text, 0, text.length(), textBounds);
        canvas.drawText(text, radiusPixels - textBounds.exactCenterX(),
                radiusPixels - textBounds.exactCenterY(), paintT);
    }

    return output;
}

From source file:Main.java

/**resource methods*/

public static Bitmap getBitmap(Context context, String url) {
    Bitmap bitmap = null;/*www .  ja  v a  2s  .  c o  m*/
    InputStream is = null;
    try {
        url = url.trim();
        if (url.indexOf("res://") == 0) {
            int sepPos = url.lastIndexOf("/");
            int resId = context.getResources().getIdentifier(url.substring(sepPos + 1),
                    url.substring(6, sepPos), context.getPackageName());
            is = context.getResources().openRawResource(resId);
        } else if (url.indexOf("file://") == 0) {
            File file = new File(url.substring(7));
            if (file.canRead())
                is = new FileInputStream(file);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        bitmap = BitmapFactory.decodeStream(is, new Rect(), options);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:Main.java

/**
 * Returns a Bitmap representing the thumbnail of the specified Bitmap. The
 * size of the thumbnail is defined by the dimension
 * android.R.dimen.launcher_application_icon_size.
 * <p>/*from w ww. j a v a  2  s.c o m*/
 * This method is not thread-safe and should be invoked on the UI thread
 * only.
 *
 * @param bitmap  The bitmap to get a thumbnail of.
 * @param context The application's context.
 * @return A thumbnail for the specified bitmap or the bitmap itself if the
 * thumbnail could not be created.
 */
public static Bitmap createThumbnailBitmap(Bitmap bitmap, Context context) {
    int sIconWidth = -1;
    int sIconHeight = -1;
    final Resources resources = context.getResources();
    sIconWidth = sIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);

    final Paint sPaint = new Paint();
    final Rect sBounds = new Rect();
    final Rect sOldBounds = new Rect();
    Canvas sCanvas = new Canvas();

    int width = sIconWidth;
    int height = sIconHeight;

    sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, Paint.FILTER_BITMAP_FLAG));

    final int bitmapWidth = bitmap.getWidth();
    final int bitmapHeight = bitmap.getHeight();

    if (width > 0 && height > 0) {
        if (width < bitmapWidth || height < bitmapHeight) {
            final float ratio = (float) bitmapWidth / bitmapHeight;

            if (bitmapWidth > bitmapHeight) {
                height = (int) (width / ratio);
            } else if (bitmapHeight > bitmapWidth) {
                width = (int) (height * ratio);
            }

            final Config c = (width == sIconWidth && height == sIconHeight) ? bitmap.getConfig()
                    : Config.ARGB_8888;
            final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
            final Canvas canvas = sCanvas;
            final Paint paint = sPaint;
            canvas.setBitmap(thumb);
            paint.setDither(false);
            paint.setFilterBitmap(true);
            sBounds.set((sIconWidth - width) / 2, (sIconHeight - height) / 2, width, height);
            sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);
            canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);
            return thumb;
        } else if (bitmapWidth < width || bitmapHeight < height) {
            final Config c = Config.ARGB_8888;
            final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
            final Canvas canvas = sCanvas;
            final Paint paint = sPaint;
            canvas.setBitmap(thumb);
            paint.setDither(false);
            paint.setFilterBitmap(true);
            canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2, (sIconHeight - bitmapHeight) / 2, paint);
            return thumb;
        }
    }

    return bitmap;
}

From source file:Main.java

private static void expandInner(final View view, final View parentView, final ViewGroup rootContainer,
        final int targtetHeight) {

    setHeight(view, 0);// w w w  .  j  av a  2  s  .  c o  m
    view.setVisibility(View.VISIBLE);
    final Animation animation = new Animation() {

        private final Rect rect = new Rect();
        private final Rect parentVisibleRect = new Rect();

        ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener;

        private final Runnable checkViewRunnable = new Runnable() {
            @Override
            public void run() {
                checkForViewInsideVisibleArea();
            }
        };

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

            int neededHeight = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT
                    : (int) (targtetHeight * interpolatedTime);
            setHeight(view, neededHeight);

            final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();

            if (globalLayoutListener == null) {
                globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {

                        if (globalLayoutListener == null) {
                            removeGlobalLayoutListener(viewTreeObserver, this);
                        }

                        checkForViewInsideVisibleArea();
                    }
                };

                viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener);
            }

            if (globalLayoutListener != null && interpolatedTime == 1) {
                runInUIThread(checkViewRunnable);
                globalLayoutListener = null;
            }

            view.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }

        private void checkForViewInsideVisibleArea() {

            if (rootContainer.indexOfChild(parentView) == -1) {
                return;
            }

            parentVisibleRect.left = 0;
            parentVisibleRect.top = 0;
            parentVisibleRect.right = parentView.getWidth();
            parentVisibleRect.bottom = parentView.getHeight();

            rootContainer.offsetDescendantRectToMyCoords(parentView, parentVisibleRect);

            if (parentVisibleRect.top < 0 || parentVisibleRect.bottom > rootContainer.getHeight()) {

                rect.left = parentView.getLeft();
                rect.top = parentView.getTop();
                rect.right = parentView.getRight();
                rect.bottom = parentView.getBottom();

                parentView.requestRectangleOnScreen(rect, true);
            }
        }
    };

    animation.setDuration(ANIMATION_DURATION);
    view.startAnimation(animation);
}

From source file:android.support.v7.internal.widget.DrawableUtils.java

/**
 * Allows us to get the optical insets for a {@link Drawable}. Since this is hidden we need to
 * use reflection. Since the {@code Insets} class is hidden also, we return a Rect instead.
 *//*  w  w  w.j a va2s . c  o  m*/
public static Rect getOpticalBounds(Drawable drawable) {
    if (sInsetsClazz != null) {
        try {
            // If the Drawable is wrapped, we need to manually unwrap it and process
            // the wrapped drawable.
            drawable = DrawableCompat.unwrap(drawable);

            final Method getOpticalInsetsMethod = drawable.getClass().getMethod("getOpticalInsets");
            final Object insets = getOpticalInsetsMethod.invoke(drawable);

            if (insets != null) {
                // If the drawable has some optical insets, let's copy them into a Rect
                final Rect result = new Rect();

                for (Field field : sInsetsClazz.getFields()) {
                    switch (field.getName()) {
                    case "left":
                        result.left = field.getInt(insets);
                        break;
                    case "top":
                        result.top = field.getInt(insets);
                        break;
                    case "right":
                        result.right = field.getInt(insets);
                        break;
                    case "bottom":
                        result.bottom = field.getInt(insets);
                        break;
                    }
                }
                return result;
            }
        } catch (Exception e) {
            // Eugh, we hit some kind of reflection issue...
            Log.e(TAG, "Couldn't obtain the optical insets. Ignoring.");
        }
    }

    // If we reach here, either we're running on a device pre-v18, the Drawable didn't have
    // any optical insets, or a reflection issue, so we'll just return an empty rect
    return INSETS_NONE;
}