Example usage for android.graphics.drawable Drawable getBounds

List of usage examples for android.graphics.drawable Drawable getBounds

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable getBounds.

Prototype

@NonNull
public final Rect getBounds() 

Source Link

Document

Return the drawable's bounds Rect.

Usage

From source file:com.linkbubble.util.Util.java

/**
 * Returns a bitmap suitable for the all apps view.
 *///from  w w  w.  j  a v a 2 s.com
static Bitmap createIconBitmap(Drawable icon, Context context) {
    synchronized (sCanvas) { // we share the statics :-(
        if (sIconWidth == -1) {
            initStatics(context);
        }

        int width = sIconWidth;
        int height = sIconHeight;

        if (icon instanceof PaintDrawable) {
            PaintDrawable painter = (PaintDrawable) icon;
            painter.setIntrinsicWidth(width);
            painter.setIntrinsicHeight(height);
        } else if (icon instanceof BitmapDrawable) {
            // Ensure the bitmap has a density.
            BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
                bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
            }
        }
        int sourceWidth = icon.getIntrinsicWidth();
        int sourceHeight = icon.getIntrinsicHeight();
        if (sourceWidth > 0 && sourceHeight > 0) {
            // There are intrinsic sizes.
            if (width < sourceWidth || height < sourceHeight) {
                // It's too big, scale it down.
                final float ratio = (float) sourceWidth / sourceHeight;
                if (sourceWidth > sourceHeight) {
                    height = (int) (width / ratio);
                } else if (sourceHeight > sourceWidth) {
                    width = (int) (height * ratio);
                }
            } else if (sourceWidth < width && sourceHeight < height) {
                // Don't scale up the icon
                width = sourceWidth;
                height = sourceHeight;
            }
        }

        // no intrinsic size --> use default size
        int textureWidth = sIconTextureWidth;
        int textureHeight = sIconTextureHeight;

        final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight, Bitmap.Config.ARGB_8888);
        final Canvas canvas = sCanvas;
        canvas.setBitmap(bitmap);

        final int left = (textureWidth - width) / 2;
        final int top = (textureHeight - height) / 2;

        @SuppressWarnings("all") // suppress dead code warning
        final boolean debug = false;
        if (debug) {
            // draw a big box for the icon for debugging
            canvas.drawColor(sColors[sColorIndex]);
            if (++sColorIndex >= sColors.length)
                sColorIndex = 0;
            Paint debugPaint = new Paint();
            debugPaint.setColor(0xffcccc00);
            canvas.drawRect(left, top, left + width, top + height, debugPaint);
        }

        sOldBounds.set(icon.getBounds());
        icon.setBounds(left, top, left + width, top + height);
        icon.draw(canvas);
        icon.setBounds(sOldBounds);
        canvas.setBitmap(null);

        return bitmap;
    }
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

/**
 * Set the state of the buttons of the wizard menu depending on the selected tab
 * @param tabPosition position of the tab
 *//*  www .  j a  v a2 s  .  c o m*/
private void setWizardMenu(int tabPosition) {

    // button background colors
    int accentColor = ContextCompat.getColor(getContext(), R.color.accent);
    int whiteColor = ContextCompat.getColor(getContext(), android.R.color.white);
    int primaryDarkColor = ContextCompat.getColor(getContext(), R.color.primary_dark);
    int primaryColor = ContextCompat.getColor(getContext(), R.color.primary);
    int redColor = ContextCompat.getColor(getContext(), R.color.dagvergunning_melding_background);

    // button icons
    Drawable leftDrawable = ContextCompat.getDrawable(getContext(), R.drawable.chevron_left_primary_dark);
    Drawable trashDrawable = ContextCompat.getDrawable(getContext(), R.drawable.delete_white);
    Drawable rightDrawable = ContextCompat.getDrawable(getContext(), R.drawable.chevron_right_primary_dark);
    Drawable checkDrawable = ContextCompat.getDrawable(getContext(), R.drawable.check_primary_dark);

    // get previous button left drawable bounds
    Drawable[] previousButtonDrawables = mWizardPreviousButton.getCompoundDrawables();
    Drawable previousButtonLeftDrawable = previousButtonDrawables[0];

    // get next button right drawable bounds
    Drawable[] nextButtonDrawables = mWizardNextButton.getCompoundDrawables();
    Drawable nextButtonRightDrawable = nextButtonDrawables[2];

    switch (tabPosition) {

    // koopman tab
    case 0:

        // previous
        if (mId == -1) {

            // new dagvergunning, so hide the delete button
            mWizardPreviousButton.setVisibility(View.INVISIBLE);
            mWizardPreviousButton.setBackgroundColor(whiteColor);
            mWizardPreviousButton.setText("");
            mWizardPreviousButton.setTextColor(primaryDarkColor);
            if (leftDrawable != null) {
                leftDrawable.setBounds(previousButtonLeftDrawable.getBounds());
                mWizardPreviousButton.setCompoundDrawables(leftDrawable, null, null, null);
            }
        } else {

            // existing dagvergunning, so show the delete button
            mWizardPreviousButton.setVisibility(View.VISIBLE);
            mWizardPreviousButton.setBackgroundColor(redColor);
            mWizardPreviousButton.setText(getString(R.string.delete));
            mWizardPreviousButton.setTextColor(whiteColor);
            if (trashDrawable != null) {
                trashDrawable.setBounds(previousButtonLeftDrawable.getBounds());
                mWizardPreviousButton.setCompoundDrawables(trashDrawable, null, null, null);
            }
        }

        // next
        mWizardNextButton.setVisibility(View.VISIBLE);
        mWizardNextButton.setBackgroundColor(accentColor);
        mWizardNextButton.setText(getString(R.string.product));
        if (rightDrawable != null) {
            rightDrawable.setBounds(nextButtonRightDrawable.getBounds());
            mWizardNextButton.setCompoundDrawables(null, null, rightDrawable, null);
        }
        break;

    // product tab
    case 1:

        // previous
        mWizardPreviousButton.setVisibility(View.VISIBLE);
        mWizardPreviousButton.setBackgroundColor(whiteColor);
        mWizardPreviousButton.setText(getString(R.string.koopman));
        mWizardPreviousButton.setTextColor(primaryDarkColor);
        if (leftDrawable != null) {
            leftDrawable.setBounds(previousButtonLeftDrawable.getBounds());
            mWizardPreviousButton.setCompoundDrawables(leftDrawable, null, null, null);
        }

        // next
        mWizardNextButton.setVisibility(View.VISIBLE);
        mWizardNextButton.setBackgroundColor(accentColor);
        mWizardNextButton.setText(getString(R.string.overzicht));
        if (rightDrawable != null) {
            rightDrawable.setBounds(nextButtonRightDrawable.getBounds());
            mWizardNextButton.setCompoundDrawables(null, null, rightDrawable, null);
        }
        break;

    // overzicht tab
    case 2:

        // previous
        mWizardPreviousButton.setVisibility(View.VISIBLE);
        mWizardPreviousButton.setBackgroundColor(whiteColor);
        mWizardPreviousButton.setText(getString(R.string.product));
        mWizardPreviousButton.setTextColor(primaryDarkColor);
        if (leftDrawable != null) {
            leftDrawable.setBounds(previousButtonLeftDrawable.getBounds());
            mWizardPreviousButton.setCompoundDrawables(leftDrawable, null, null, null);
        }

        // next
        mWizardNextButton.setVisibility(View.VISIBLE);
        mWizardNextButton.setBackgroundColor(primaryColor);
        mWizardNextButton.setTextColor(primaryDarkColor);
        mWizardNextButton.setText(getString(R.string.save));
        if (checkDrawable != null) {
            checkDrawable.setBounds(nextButtonRightDrawable.getBounds());
            mWizardNextButton.setCompoundDrawables(null, null, checkDrawable, null);
        }
        break;

    default:
        break;
    }
}

From source file:rikka.akashitoolkit.ui.widget.IconSwitchCompat.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    final Rect padding = mTempRect;
    final Drawable trackDrawable = mTrackDrawable;
    if (trackDrawable != null) {
        trackDrawable.getPadding(padding);
    } else {/*from  w  ww .  j  av  a  2  s .  co  m*/
        padding.setEmpty();
    }

    final int switchTop = mSwitchTop;
    final int switchBottom = mSwitchBottom;
    final int switchInnerTop = switchTop + padding.top;
    final int switchInnerBottom = switchBottom - padding.bottom;

    final Drawable thumbDrawable = mThumbDrawable;
    if (trackDrawable != null) {
        if (mSplitTrack && thumbDrawable != null) {
            final Rect insets = DrawableUtils.getOpticalBounds(thumbDrawable);
            thumbDrawable.copyBounds(padding);
            padding.left += insets.left;
            padding.right -= insets.right;

            final int saveCount = canvas.save();
            canvas.clipRect(padding, Region.Op.DIFFERENCE);
            trackDrawable.draw(canvas);
            canvas.restoreToCount(saveCount);
        } else {
            trackDrawable.draw(canvas);
        }
    }

    final int saveCount = canvas.save();

    if (thumbDrawable != null) {
        thumbDrawable.draw(canvas);
    }

    final Drawable iconDrawable = mIconDrawable;
    if (iconDrawable != null) {
        if (mSplitTrack) {
            final Rect insets = DrawableUtils.getOpticalBounds(iconDrawable);
            iconDrawable.copyBounds(padding);
            padding.left += insets.left;
            padding.right -= insets.right;

            //final int saveCount = canvas.save();
            canvas.clipRect(padding, Region.Op.DIFFERENCE);
            iconDrawable.draw(canvas);
            canvas.restoreToCount(saveCount);
        } else {
            iconDrawable.draw(canvas);
        }
    }

    final Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;
    if (switchText != null) {
        final int drawableState[] = getDrawableState();
        if (mTextColors != null) {
            mTextPaint.setColor(mTextColors.getColorForState(drawableState, 0));
        }
        mTextPaint.drawableState = drawableState;

        final int cX;
        if (thumbDrawable != null) {
            final Rect bounds = thumbDrawable.getBounds();
            cX = bounds.left + bounds.right;
        } else {
            cX = getWidth();
        }

        final int left = cX / 2 - switchText.getWidth() / 2;
        final int top = (switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2;
        canvas.translate(left, top);
        switchText.draw(canvas);
    }

    canvas.restoreToCount(saveCount);
}

From source file:com.android.launcher3.Utilities.java

/**
 * @param scale the scale to apply before drawing {@param icon} on the canvas
 *///from ww w. j  a  v a 2  s .  com
public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
    synchronized (sCanvas) {
        final int iconBitmapSize = getIconBitmapSize();

        int width = iconBitmapSize;
        int height = iconBitmapSize;

        if (icon instanceof PaintDrawable) {
            PaintDrawable painter = (PaintDrawable) icon;
            painter.setIntrinsicWidth(width);
            painter.setIntrinsicHeight(height);
        } else if (icon instanceof BitmapDrawable) {
            // Ensure the bitmap has a density.
            BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
                bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
            }
        }
        int sourceWidth = icon.getIntrinsicWidth();
        int sourceHeight = icon.getIntrinsicHeight();
        if (sourceWidth > 0 && sourceHeight > 0) {
            // Scale the icon proportionally to the icon dimensions
            final float ratio = (float) sourceWidth / sourceHeight;
            if (sourceWidth > sourceHeight) {
                height = (int) (width / ratio);
            } else if (sourceHeight > sourceWidth) {
                width = (int) (height * ratio);
            }
        }

        // no intrinsic size --> use default size
        int textureWidth = iconBitmapSize;
        int textureHeight = iconBitmapSize;

        final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight, Bitmap.Config.ARGB_8888);
        final Canvas canvas = sCanvas;
        canvas.setBitmap(bitmap);

        final int left = (textureWidth - width) / 2;
        final int top = (textureHeight - height) / 2;

        @SuppressWarnings("all") // suppress dead code warning
        final boolean debug = false;
        if (debug) {
            // draw a big box for the icon for debugging
            canvas.drawColor(sColors[sColorIndex]);
            if (++sColorIndex >= sColors.length)
                sColorIndex = 0;
            Paint debugPaint = new Paint();
            debugPaint.setColor(0xffcccc00);
            canvas.drawRect(left, top, left + width, top + height, debugPaint);
        }

        sOldBounds.set(icon.getBounds());
        icon.setBounds(left, top, left + width, top + height);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
        icon.draw(canvas);
        canvas.restore();
        icon.setBounds(sOldBounds);
        canvas.setBitmap(null);

        return bitmap;
    }
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java

@CallSuper
protected void onBufferDraw(Canvas canvas, final Paint paint) {
    if (mKeyboardChanged) {
        invalidateAllKeys();//from  w w  w  . j a va  2 s.  c om
        mKeyboardChanged = false;
    }

    canvas.getClipBounds(mDirtyRect);

    if (mKeyboard == null)
        return;

    final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f)
            && AnyApplication.getConfig().getShowKeyboardNameText();

    final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys();

    final boolean useCustomKeyTextColor = false;
    // TODO: final boolean useCustomKeyTextColor =
    // AnyApplication.getConfig().getUseCustomTextColorOnKeys();
    final ColorStateList keyTextColor = useCustomKeyTextColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFF6666FF })
            : mKeyTextColor;

    final boolean useCustomHintColor = drawHintText && false;
    // TODO: final boolean useCustomHintColor = drawHintText &&
    final ColorStateList hintColor = useCustomHintColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFFFF6666 })
            : mHintTextColor;

    // allow preferences to override theme settings for hint text position
    final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign();
    final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintAlign()
            : mHintLabelAlign;
    final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintVAlign()
            : mHintLabelVAlign;

    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final int kbdPaddingLeft = getPaddingLeft();
    final int kbdPaddingTop = getPaddingTop();
    final Key[] keys = mKeys;
    final Key invalidKey = mInvalidatedKey;

    boolean drawSingleKey = false;
    if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
        // TODO we should use Rect.inset and Rect.contains here.
        // Is clipRegion completely contained within the invalidated key?
        if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
                && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
                && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
                && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
            drawSingleKey = true;
        }
    }

    for (Key keyBase : keys) {
        final AnyKey key = (AnyKey) keyBase;
        final boolean keyIsSpace = isSpaceKey(key);

        if (drawSingleKey && (invalidKey != key)) {
            continue;
        }
        if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop,
                key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);

        if (keyIsSpace)
            paint.setColor(mKeyboardNameTextColor);
        else
            paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
        keyBackground.setState(drawableState);

        // Switch the character to uppercase if shift is pressed
        CharSequence label = key.label == null ? null : adjustLabelToShiftState(key);

        final Rect bounds = keyBackground.getBounds();
        if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }
        canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
        keyBackground.draw(canvas);

        if (TextUtils.isEmpty(label)) {
            Drawable iconToDraw = getIconToDrawForKey(key, false);
            if (iconToDraw != null/* && shouldDrawIcon */) {
                //http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
                //http://stackoverflow.com/a/103600/1324235
                final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;

                // Special handing for the upper-right number hint icons
                final int drawableWidth;
                final int drawableHeight;
                final int drawableX;
                final int drawableY;

                drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
                drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
                drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right
                        - drawableWidth) / 2;
                drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom
                        - drawableHeight) / 2;

                canvas.translate(drawableX, drawableY);
                iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
                iconToDraw.draw(canvas);
                canvas.translate(-drawableX, -drawableY);
                if (keyIsSpace && drawKeyboardNameText) {
                    // now a little hack, I'll set the label now, so it get
                    // drawn.
                    label = mKeyboardName;
                }
            } else {
                // ho... no icon.
                // I'll try to guess the text
                label = guessLabelForKey(key.getPrimaryCode());
            }
        }

        if (label != null) {
            // For characters, use large font. For labels like "Done", use
            // small font.
            final FontMetrics fm;
            if (keyIsSpace) {
                paint.setTextSize(mKeyboardNameTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mKeyboardNameFontMetrics == null)
                    mKeyboardNameFontMetrics = paint.getFontMetrics();
                fm = mKeyboardNameFontMetrics;
            } else if (label.length() > 1 && key.getCodesCount() < 2) {
                setPaintForLabelText(paint);
                if (mLabelFontMetrics == null)
                    mLabelFontMetrics = paint.getFontMetrics();
                fm = mLabelFontMetrics;
            } else {
                setPaintToKeyText(paint);
                if (mTextFontMetrics == null)
                    mTextFontMetrics = paint.getFontMetrics();
                fm = mTextFontMetrics;
            }

            if (isLabelOfPictographic(label)) {
                paint.setTextSize(2f * paint.getTextSize());
            }

            final float labelHeight = -fm.top;
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor);

            final float textWidth = adjustTextSizeForLabel(paint, label, key.width);

            // the center of the drawable space, which is value used
            // previously for vertically
            // positioning the key label
            final float centerY = mKeyBackgroundPadding.top
                    + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom)
                            / (keyIsSpace ? 3 : 2));// the label on the space is a bit higher

            // the X coordinate for the center of the main label text is
            // unaffected by the hints
            final float textX = mKeyBackgroundPadding.left
                    + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
            final float textY;
            // Some devices (mostly pre-Honeycomb, have issues with RTL text
            // drawing.
            // Of course, there is no issue with a single character :)
            // so, we'll use the RTL secured drawing (via StaticLayout) for
            // labels.
            if (label.length() > 1 && !AnyApplication.getConfig().workaround_alwaysUseDrawText()) {
                // calculate Y coordinate of top of text based on center
                // location
                textY = centerY - ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                // RTL fix. But it costs, let do it when in need (more than
                // 1 character)
                StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth,
                        Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                labelText.draw(canvas);
            } else {
                // to get Y coordinate of baseline from center of text,
                // first add half the height (to get to
                // bottom of text), then subtract the part below the
                // baseline. Note that fm.top is negative.
                textY = centerY + ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                canvas.drawText(label, 0, label.length(), 0, 0, paint);
            }
            canvas.translate(-textX, -textY);
            // (-)

            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        }

        if (drawHintText) {
            if ((key.popupCharacters != null && key.popupCharacters.length() > 0) || (key.popupResId != 0)
                    || (key.longPressCode != 0)) {
                Align oldAlign = paint.getTextAlign();

                String hintText = null;

                if (key.hintLabel != null && key.hintLabel.length() > 0) {
                    hintText = key.hintLabel.toString();
                    // it is the responsibility of the keyboard layout
                    // designer to ensure that they do
                    // not put too many characters in the hint label...
                } else if (key.longPressCode != 0) {
                    if (Character.isLetterOrDigit(key.longPressCode))
                        hintText = Character.toString((char) key.longPressCode);
                } else if (key.popupCharacters != null) {
                    final String hintString = key.popupCharacters.toString();
                    final int hintLength = hintString.length();
                    if (hintLength <= 3)
                        hintText = hintString;
                }

                // if hintText is still null, it means it didn't fit one of
                // the above
                // cases, so we should provide the hint using the default
                if (hintText == null) {
                    if (mHintOverflowLabel != null)
                        hintText = mHintOverflowLabel;
                    else {
                        // theme does not provide a defaultHintLabel
                        // use  if hints are above, ... if hints are
                        // below
                        // (to avoid being too close to main label/icon)
                        if (hintVAlign == Gravity.TOP)
                            hintText = "";
                        else
                            hintText = "...";
                    }
                }

                if (mKeyboard.isShifted())
                    hintText = hintText.toUpperCase(getKeyboard().getLocale());

                // now draw hint
                paint.setTypeface(Typeface.DEFAULT);
                paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000));
                paint.setTextSize(mHintTextSize);
                // get the hint text font metrics so that we know the size
                // of the hint when
                // we try to position the main label (to try to make sure
                // they don't overlap)
                if (mHintTextFontMetrics == null) {
                    mHintTextFontMetrics = paint.getFontMetrics();
                }

                final float hintX;
                final float hintY;

                // the (float) 0.5 value is added or subtracted to just give
                // a little more room
                // in case the theme designer didn't account for the hint
                // label location
                if (hintAlign == Gravity.START) {
                    // left
                    paint.setTextAlign(Align.LEFT);
                    hintX = mKeyBackgroundPadding.left + 0.5f;
                } else if (hintAlign == Gravity.CENTER) {
                    // center
                    paint.setTextAlign(Align.CENTER);
                    hintX = mKeyBackgroundPadding.left
                            + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
                } else {
                    // right
                    paint.setTextAlign(Align.RIGHT);
                    hintX = key.width - mKeyBackgroundPadding.right - 0.5f;
                }

                if (hintVAlign == Gravity.TOP) {
                    // above
                    hintY = mKeyBackgroundPadding.top - mHintTextFontMetrics.top + 0.5f;
                } else {
                    // below
                    hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFontMetrics.bottom - 0.5f;
                }

                canvas.drawText(hintText, hintX, hintY, paint);
                paint.setTextAlign(oldAlign);
            }
        }

        canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
    }
    mInvalidatedKey = null;

    mDirtyRect.setEmpty();
}

From source file:com.yek.keyboard.keyboards.views.AnyKeyboardViewBase.java

@CallSuper
protected void onBufferDraw(Canvas canvas, final Paint paint) {
    if (mKeyboardChanged) {
        invalidateAllKeys();// ww  w.j  a v a2s .co m
        mKeyboardChanged = false;
    }

    canvas.getClipBounds(mDirtyRect);

    if (mKeyboard == null)
        return;

    final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f)
            && AnyApplication.getConfig().getShowKeyboardNameText();

    final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys();

    final boolean useCustomKeyTextColor = false;
    // TODO: final boolean useCustomKeyTextColor =
    // AnyApplication.getConfig().getUseCustomTextColorOnKeys();
    final ColorStateList keyTextColor = useCustomKeyTextColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFF6666FF })
            : mKeyTextColor;

    final boolean useCustomHintColor = drawHintText && false;
    // TODO: final boolean useCustomHintColor = drawHintText &&
    final ColorStateList hintColor = useCustomHintColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFFFF6666 })
            : mHintTextColor;

    // allow preferences to override theme settings for hint text position
    final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign();
    final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintAlign()
            : mHintLabelAlign;
    final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintVAlign()
            : mHintLabelVAlign;

    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final int kbdPaddingLeft = getPaddingLeft();
    final int kbdPaddingTop = getPaddingTop();
    final Keyboard.Key[] keys = mKeys;
    final Keyboard.Key invalidKey = mInvalidatedKey;

    boolean drawSingleKey = false;
    if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
        // TODO we should use Rect.inset and Rect.contains here.
        // Is clipRegion completely contained within the invalidated key?
        if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
                && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
                && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
                && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
            drawSingleKey = true;
        }
    }

    for (Keyboard.Key keyBase : keys) {
        final AnyKeyboard.AnyKey key = (AnyKeyboard.AnyKey) keyBase;
        final boolean keyIsSpace = isSpaceKey(key);

        if (drawSingleKey && (invalidKey != key)) {
            continue;
        }
        if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop,
                key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);

        if (keyIsSpace)
            paint.setColor(mKeyboardNameTextColor);
        else
            paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
        keyBackground.setState(drawableState);

        // Switch the character to uppercase if shift is pressed
        CharSequence label = key.label == null ? null : adjustLabelToShiftState(key);

        final Rect bounds = keyBackground.getBounds();
        if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }
        canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
        keyBackground.draw(canvas);

        if (TextUtils.isEmpty(label)) {
            Drawable iconToDraw = getIconToDrawForKey(key, false);
            if (iconToDraw != null/* && shouldDrawIcon */) {
                //http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
                //http://stackoverflow.com/a/103600/1324235
                final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;

                // Special handing for the upper-right number hint icons
                final int drawableWidth;
                final int drawableHeight;
                final int drawableX;
                final int drawableY;

                drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
                drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
                drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right
                        - drawableWidth) / 2;
                drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom
                        - drawableHeight) / 2;

                canvas.translate(drawableX, drawableY);
                iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
                iconToDraw.draw(canvas);
                canvas.translate(-drawableX, -drawableY);
                if (keyIsSpace && drawKeyboardNameText) {
                    // now a little hack, I'll set the label now, so it get
                    // drawn.
                    label = mKeyboardName;
                }
            } else {
                // ho... no icon.
                // I'll try to guess the text
                label = guessLabelForKey(key.getPrimaryCode());
            }
        }

        if (label != null) {
            // For characters, use large font. For labels like "Done", use
            // small font.
            final FontMetrics fm;
            if (keyIsSpace) {
                paint.setTextSize(mKeyboardNameTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mKeyboardNameFM == null)
                    mKeyboardNameFM = paint.getFontMetrics();
                fm = mKeyboardNameFM;
            } else if (label.length() > 1 && key.getCodesCount() < 2) {
                setPaintForLabelText(paint);
                if (mLabelFM == null)
                    mLabelFM = paint.getFontMetrics();
                fm = mLabelFM;
            } else {
                setPaintToKeyText(paint);
                if (mTextFM == null)
                    mTextFM = paint.getFontMetrics();
                fm = mTextFM;
            }

            if (isLabelOfPictographic(label)) {
                paint.setTextSize(2f * paint.getTextSize());
            }

            final float labelHeight = -fm.top;
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor);

            final float textWidth = adjustTextSizeForLabel(paint, label, key.width);

            // the center of the drawable space, which is value used
            // previously for vertically
            // positioning the key label
            final float centerY = mKeyBackgroundPadding.top
                    + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom)
                            / (keyIsSpace ? 3 : 2));// the label on the space is a bit higher

            // the X coordinate for the center of the main label text is
            // unaffected by the hints
            final float textX = mKeyBackgroundPadding.left
                    + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
            final float textY;
            // Some devices (mostly pre-Honeycomb, have issues with RTL text
            // drawing.
            // Of course, there is no issue with a single character :)
            // so, we'll use the RTL secured drawing (via StaticLayout) for
            // labels.
            if (label.length() > 1 && !AnyApplication.getConfig().workaround_alwaysUseDrawText()) {
                // calculate Y coordinate of top of text based on center
                // location
                textY = centerY - ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                // RTL fix. But it costs, let do it when in need (more than
                // 1 character)
                StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth,
                        Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                labelText.draw(canvas);
            } else {
                // to get Y coordinate of baseline from center of text,
                // first add half the height (to get to
                // bottom of text), then subtract the part below the
                // baseline. Note that fm.top is negative.
                textY = centerY + ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                canvas.drawText(label, 0, label.length(), 0, 0, paint);
            }
            canvas.translate(-textX, -textY);
            // (-)

            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        }

        if (drawHintText) {
            if ((key.popupCharacters != null && key.popupCharacters.length() > 0) || (key.popupResId != 0)
                    || (key.longPressCode != 0)) {
                Align oldAlign = paint.getTextAlign();

                String hintText = null;

                if (key.hintLabel != null && key.hintLabel.length() > 0) {
                    hintText = key.hintLabel.toString();
                    // it is the responsibility of the keyboard layout
                    // designer to ensure that they do
                    // not put too many characters in the hint label...
                } else if (key.longPressCode != 0) {
                    if (Character.isLetterOrDigit(key.longPressCode))
                        hintText = Character.toString((char) key.longPressCode);
                } else if (key.popupCharacters != null) {
                    final String hintString = key.popupCharacters.toString();
                    final int hintLength = hintString.length();
                    if (hintLength <= 3)
                        hintText = hintString;
                }

                // if hintText is still null, it means it didn't fit one of
                // the above
                // cases, so we should provide the hint using the default
                if (hintText == null) {
                    if (mHintOverflowLabel != null)
                        hintText = mHintOverflowLabel;
                    else {
                        // theme does not provide a defaultHintLabel
                        // use  if hints are above, ... if hints are
                        // below
                        // (to avoid being too close to main label/icon)
                        if (hintVAlign == Gravity.TOP)
                            hintText = "";
                        else
                            hintText = "...";
                    }
                }

                if (mKeyboard.isShifted())
                    hintText = hintText.toUpperCase(getKeyboard().getLocale());

                // now draw hint
                paint.setTypeface(Typeface.DEFAULT);
                paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000));
                paint.setTextSize(mHintTextSize);
                // get the hint text font metrics so that we know the size
                // of the hint when
                // we try to position the main label (to try to make sure
                // they don't overlap)
                if (mHintTextFM == null) {
                    mHintTextFM = paint.getFontMetrics();
                }

                final float hintX;
                final float hintY;

                // the (float) 0.5 value is added or subtracted to just give
                // a little more room
                // in case the theme designer didn't account for the hint
                // label location
                if (hintAlign == Gravity.START) {
                    // left
                    paint.setTextAlign(Align.LEFT);
                    hintX = mKeyBackgroundPadding.left + 0.5f;
                } else if (hintAlign == Gravity.CENTER) {
                    // center
                    paint.setTextAlign(Align.CENTER);
                    hintX = mKeyBackgroundPadding.left
                            + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
                } else {
                    // right
                    paint.setTextAlign(Align.RIGHT);
                    hintX = key.width - mKeyBackgroundPadding.right - 0.5f;
                }

                if (hintVAlign == Gravity.TOP) {
                    // above
                    hintY = mKeyBackgroundPadding.top - mHintTextFM.top + 0.5f;
                } else {
                    // below
                    hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - 0.5f;
                }

                canvas.drawText(hintText, hintX, hintY, paint);
                paint.setTextAlign(oldAlign);
            }
        }

        canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
    }
    mInvalidatedKey = null;

    mDirtyRect.setEmpty();
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardBaseView.java

private void onBufferDraw(Canvas canvas) {
    if (mKeyboardChanged) {
        invalidateAllKeys();/*  w w w .j  a  v  a2s.  c  o  m*/
        mKeyboardChanged = false;
    }

    canvas.getClipBounds(mDirtyRect);

    if (mKeyboard == null)
        return;

    final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f)
            && AnyApplication.getConfig().getShowKeyboardNameText();

    final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys();
    // TODO: calls to AnyApplication.getConfig().getXXXXX() functions are
    // not yet implemented,
    // but need to when allowing preferences to override theme settings of
    // these values
    // right now just using what should be the default values for these
    // unimplemented preferences

    final boolean useCustomKeyTextColor = false;
    // TODO: final boolean useCustomKeyTextColor =
    // AnyApplication.getConfig().getUseCustomTextColorOnKeys();
    final ColorStateList keyTextColor = useCustomKeyTextColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFF6666FF })
            : mKeyTextColor;
    // TODO: ? AnyApplication.getConfig().getCustomKeyTextColorOnKeys() :
    // mKeyTextColor;

    final boolean useCustomHintColor = drawHintText && false;
    // TODO: final boolean useCustomHintColor = drawHintText &&
    // AnyApplication.getConfig().getUseCustomHintColorOnKeys();
    final ColorStateList hintColor = useCustomHintColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFFFF6666 })
            : mHintTextColor;
    // TODO: ? AnyApplication.getConfig().getCustomHintColorOnKeys() :
    // mHintTextColor;

    // allow preferences to override theme settings for hint text position
    final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign();
    final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintAlign()
            : mHintLabelAlign;
    final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintVAlign()
            : mHintLabelVAlign;

    final Paint paint = mPaint;
    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final int kbdPaddingLeft = getPaddingLeft();
    final int kbdPaddingTop = getPaddingTop();
    final Key[] keys = mKeys;
    final Key invalidKey = mInvalidatedKey;

    boolean drawSingleKey = false;
    if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
        // TODO we should use Rect.inset and Rect.contains here.
        // Is clipRegion completely contained within the invalidated key?
        if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
                && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
                && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
                && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
            drawSingleKey = true;
        }
    }
    final int keyCount = keys.length;
    for (int i = 0; i < keyCount; i++) {
        final AnyKey key = (AnyKey) keys[i];
        final boolean keyIsSpace = isSpaceKey(key);

        if (drawSingleKey && (invalidKey != key)) {
            continue;
        }
        if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop,
                key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);

        if (keyIsSpace)
            paint.setColor(mKeyboardNameTextColor.getColorForState(drawableState, 0xFF000000));
        else
            paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
        keyBackground.setState(drawableState);

        // Switch the character to uppercase if shift is pressed
        CharSequence label = key.label == null ? null : adjustCase(key).toString();

        final Rect bounds = keyBackground.getBounds();
        if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }
        canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
        keyBackground.draw(canvas);

        if (TextUtils.isEmpty(label)) {
            Drawable iconToDraw = getIconToDrawForKey(key, false);
            if (iconToDraw != null/* && shouldDrawIcon */) {
                //http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
                //http://stackoverflow.com/a/103600/1324235
                final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;

                // Special handing for the upper-right number hint icons
                final int drawableWidth;
                final int drawableHeight;
                final int drawableX;
                final int drawableY;

                drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
                drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
                drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right
                        - drawableWidth) / 2;
                drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom
                        - drawableHeight) / 2;

                canvas.translate(drawableX, drawableY);
                iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
                iconToDraw.draw(canvas);
                canvas.translate(-drawableX, -drawableY);
                if (keyIsSpace && drawKeyboardNameText) {
                    // now a little hack, I'll set the label now, so it get
                    // drawn.
                    label = mKeyboardName;
                }
            } else {
                // ho... no icon.
                // I'll try to guess the text
                label = guessLabelForKey(key.codes[0]);
                if (TextUtils.isEmpty(label)) {
                    Log.w(TAG, "That's unfortunate, for key " + key.codes[0] + " at (" + key.x + ", " + key.y
                            + ") there is no icon nor label. Action ID is " + mKeyboardActionType);
                }
            }
        }

        if (label != null) {
            // For characters, use large font. For labels like "Done", use
            // small font.
            final FontMetrics fm;
            if (keyIsSpace) {
                paint.setTextSize(mKeyboardNameTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mKeyboardNameFM == null)
                    mKeyboardNameFM = paint.getFontMetrics();
                fm = mKeyboardNameFM;
            } else if (label.length() > 1 && key.codes.length < 2) {
                paint.setTextSize(mLabelTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mLabelFM == null)
                    mLabelFM = paint.getFontMetrics();
                fm = mLabelFM;
            } else {
                fm = setPaintToKeyText(paint);
            }

            final float labelHeight = -fm.top;
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor);

            // (+)This is the trick to get RTL/LTR text correct
            // no matter what: StaticLayout
            // this should be in the top left corner of the key
            float textWidth = paint.measureText(label, 0, label.length());
            // I'm going to try something if the key is too small for the
            // text:
            // 1) divide the text size by 1.5
            // 2) if still too large, divide by 2.5
            // 3) show no text
            if (textWidth > key.width) {
                Log.d(TAG, "Label '" + label + "' is too large for the key. Reducing by 1.5.");
                paint.setTextSize(mKeyTextSize / 1.5f);
                textWidth = paint.measureText(label, 0, label.length());
                if (textWidth > key.width) {
                    Log.d(TAG, "Label '" + label + "' is too large for the key. Reducing by 2.5.");
                    paint.setTextSize(mKeyTextSize / 2.5f);
                    textWidth = paint.measureText(label, 0, label.length());
                    if (textWidth > key.width) {
                        Log.d(TAG, "Label '" + label + "' is too large for the key. Showing no text.");
                        paint.setTextSize(0f);
                        textWidth = paint.measureText(label, 0, label.length());
                    }
                }
            }

            // the center of the drawable space, which is value used
            // previously for vertically
            // positioning the key label
            final float centerY = mKeyBackgroundPadding.top
                    + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom)
                            / (keyIsSpace ? 3 : 2));// the label on the space is a bit higher

            // the X coordinate for the center of the main label text is
            // unaffected by the hints
            final float centerX = mKeyBackgroundPadding.left
                    + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;

            final float textX = centerX;
            final float textY;
            // Some devices (mostly pre-Honeycomb, have issues with RTL text
            // drawing.
            // Of course, there is no issue with a single character :)
            // so, we'll use the RTL secured drawing (via StaticLayout) for
            // labels.
            if (label.length() > 1 && !AnyApplication.getConfig().workaround_alwaysUseDrawText()) {
                // calculate Y coordinate of top of text based on center
                // location
                textY = centerY - ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                Log.d(TAG, "Using RTL fix for key draw '" + label + "'");
                // RTL fix. But it costs, let do it when in need (more than
                // 1 character)
                StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth,
                        Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                labelText.draw(canvas);
            } else {
                // to get Y coordinate of baseline from center of text,
                // first add half the height (to get to
                // bottom of text), then subtract the part below the
                // baseline. Note that fm.top is negative.
                textY = centerY + ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                canvas.drawText(label, 0, label.length(), 0, 0, paint);
            }
            canvas.translate(-textX, -textY);
            // (-)

            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        }

        if (drawHintText) {
            if ((key.popupCharacters != null && key.popupCharacters.length() > 0) || (key.popupResId != 0)
                    || (key.longPressCode != 0)) {
                Paint.Align oldAlign = paint.getTextAlign();

                String hintText = null;

                if (key.hintLabel != null && key.hintLabel.length() > 0) {
                    hintText = key.hintLabel.toString();
                    // it is the responsibility of the keyboard layout
                    // designer to ensure that they do
                    // not put too many characters in the hint label...
                } else if (key.longPressCode != 0) {
                    if (Character.isLetterOrDigit(key.longPressCode))
                        hintText = Character.toString((char) key.longPressCode);
                } else if (key.popupCharacters != null) {
                    final String hintString = key.popupCharacters.toString();
                    final int hintLength = hintString.length();
                    if (hintLength <= 3)
                        hintText = hintString;
                }

                // if hintText is still null, it means it didn't fit one of
                // the above
                // cases, so we should provide the hint using the default
                if (hintText == null) {
                    if (mHintOverflowLabel != null)
                        hintText = mHintOverflowLabel.toString();
                    else {
                        // theme does not provide a defaultHintLabel
                        // use  if hints are above, ... if hints are
                        // below
                        // (to avoid being too close to main label/icon)
                        if (hintVAlign == Gravity.TOP)
                            hintText = "";
                        else
                            hintText = "...";
                    }
                }

                if (mKeyboard.isShifted())
                    hintText = hintText.toUpperCase();

                // now draw hint
                paint.setTypeface(Typeface.DEFAULT);
                paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000));
                paint.setTextSize(mHintTextSize);
                // get the hint text font metrics so that we know the size
                // of the hint when
                // we try to position the main label (to try to make sure
                // they don't overlap)
                if (mHintTextFM == null) {
                    mHintTextFM = paint.getFontMetrics();
                }

                final float hintX;
                final float hintY;

                // the (float) 0.5 value is added or subtracted to just give
                // a little more room
                // in case the theme designer didn't account for the hint
                // label location
                if (hintAlign == Gravity.LEFT) {
                    // left
                    paint.setTextAlign(Paint.Align.LEFT);
                    hintX = mKeyBackgroundPadding.left + (float) 0.5;
                } else if (hintAlign == Gravity.CENTER) {
                    // center
                    paint.setTextAlign(Paint.Align.CENTER);
                    hintX = mKeyBackgroundPadding.left
                            + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
                } else {
                    // right
                    paint.setTextAlign(Paint.Align.RIGHT);
                    hintX = key.width - mKeyBackgroundPadding.right - (float) 0.5;
                }

                if (hintVAlign == Gravity.TOP) {
                    // above
                    hintY = mKeyBackgroundPadding.top - mHintTextFM.top + (float) 0.5;
                } else {
                    // below
                    hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - (float) 0.5;
                }

                canvas.drawText(hintText, hintX, hintY, paint);
                paint.setTextAlign(oldAlign);
            }
        }

        canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
    }
    mInvalidatedKey = null;
    // Overlay a dark rectangle to dim the keyboard
    if (mMiniKeyboard != null && mMiniKeyboardVisible) {
        paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    }

    if (FeaturesSet.DEBUG_LOG) {
        if (mShowTouchPoints) {
            for (PointerTracker tracker : mPointerTrackers) {
                int startX = tracker.getStartX();
                int startY = tracker.getStartY();
                int lastX = tracker.getLastX();
                int lastY = tracker.getLastY();
                paint.setAlpha(128);
                paint.setColor(0xFFFF0000);
                canvas.drawCircle(startX, startY, 3, paint);
                canvas.drawLine(startX, startY, lastX, lastY, paint);
                paint.setColor(0xFF0000FF);
                canvas.drawCircle(lastX, lastY, 3, paint);
                paint.setColor(0xFF00FF00);
                canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint);
            }
        }
    }

    mDrawPending = false;
    mDirtyRect.setEmpty();
}

From source file:com.android.launcher3.Launcher.java

private Bundle getActivityLaunchOptions(View v) {
    if (Utilities.ATLEAST_MARSHMALLOW) {
        int left = 0, top = 0;
        int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
        if (v instanceof TextView) {
            // Launch from center of icon, not entire view
            Drawable icon = Workspace.getTextViewIcon((TextView) v);
            if (icon != null) {
                Rect bounds = icon.getBounds();
                left = (width - bounds.width()) / 2;
                top = v.getPaddingTop();
                width = bounds.width();/*from w  w  w  . j a  v a2 s  . c  o  m*/
                height = bounds.height();
            }
        }
        return ActivityOptions.makeClipRevealAnimation(v, left, top, width, height).toBundle();
    } else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
        // On L devices, we use the device default slide-up transition.
        // On L MR1 devices, we use a custom version of the slide-up transition which
        // doesn't have the delay present in the device default.
        return ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim).toBundle();
    }
    return null;
}

From source file:com.klinker.android.launcher.launcher3.Launcher.java

private boolean startActivity(View v, Intent intent, Object tag) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {//ww  w  .j  a  v a 2s  .  co m
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
        UserManagerCompat userManager = UserManagerCompat.getInstance(this);

        UserHandleCompat user = null;
        if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
            long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
            user = userManager.getUserForSerialNumber(serialNumber);
        }

        Bundle optsBundle = null;
        if (useLaunchAnimation) {
            ActivityOptions opts = null;
            if (sClipRevealMethod != null) {
                // TODO: call method directly when Launcher3 can depend on M APIs
                int left = 0, top = 0;
                int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
                if (v instanceof TextView) {
                    // Launch from center of icon, not entire view
                    Drawable icon = Workspace.getTextViewIcon((TextView) v);
                    if (icon != null) {
                        Rect bounds = icon.getBounds();
                        left = (width - bounds.width()) / 2;
                        top = v.getPaddingTop();
                        width = bounds.width();
                        height = bounds.height();
                    }
                }
                try {
                    opts = (ActivityOptions) sClipRevealMethod.invoke(null, v, left, top, width, height);
                } catch (IllegalAccessException e) {
                    Log.d(TAG, "Could not call makeClipRevealAnimation: " + e);
                    sClipRevealMethod = null;
                } catch (InvocationTargetException e) {
                    Log.d(TAG, "Could not call makeClipRevealAnimation: " + e);
                    sClipRevealMethod = null;
                }
            }
            if (opts == null && !Utilities.isLmpOrAbove()) {
                // Below L, we use a scale up animation
                opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(),
                        v.getMeasuredHeight());
            } else if (opts == null && Utilities.isLmpMR1()) {
                // On L devices, we use the device default slide-up transition.
                // On L MR1 devices, we a custom version of the slide-up transition which
                // doesn't have the delay present in the device default.
                opts = ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim);
            }
            optsBundle = opts != null ? opts.toBundle() : null;
        }

        if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
            // Could be launching some bookkeeping activity
            startActivity(intent, optsBundle);
        } else {
            // TODO Component can be null when shortcuts are supported for secondary user
            launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(),
                    optsBundle);
        }
        return true;
    } catch (SecurityException e) {
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Launcher does not have the permission to launch " + intent
                + ". Make sure to create a MAIN intent-filter for the corresponding activity "
                + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e);
    }
    return false;
}

From source file:xyz.klinker.blur.launcher3.Launcher.java

private boolean startActivity(View v, Intent intent, Object tag) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {/*from  www .jav  a  2  s .  c o  m*/
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
        UserManagerCompat userManager = UserManagerCompat.getInstance(this);

        UserHandleCompat user = null;
        if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
            long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
            user = userManager.getUserForSerialNumber(serialNumber);
        }

        Bundle optsBundle = null;
        if (useLaunchAnimation) {
            ActivityOptions opts = null;
            if (Utilities.ATLEAST_MARSHMALLOW) {
                int left = 0, top = 0;
                int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
                if (v instanceof TextView) {
                    // Launch from center of icon, not entire view
                    Drawable icon = Workspace.getTextViewIcon((TextView) v);
                    if (icon != null) {
                        Rect bounds = icon.getBounds();
                        left = (width - bounds.width()) / 2;
                        top = v.getPaddingTop();
                        width = bounds.width();
                        height = bounds.height();
                    }
                }
                opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
            } else if (!Utilities.ATLEAST_LOLLIPOP) {
                // Below L, we use a scale up animation
                opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(),
                        v.getMeasuredHeight());
            } else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
                // On L devices, we use the device default slide-up transition.
                // On L MR1 devices, we a custom version of the slide-up transition which
                // doesn't have the delay present in the device default.
                opts = ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim);
            }
            optsBundle = opts != null ? opts.toBundle() : null;
        }

        if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
            StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                // Temporarily disable deathPenalty on all default checks. For eg, shortcuts
                // containing file Uris would cause a crash as penaltyDeathOnFileUriExposure
                // is enabled by default on NYC.
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
                // Could be launching some bookkeeping activity
                startActivity(intent, optsBundle);
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }
        } else {
            // TODO Component can be null when shortcuts are supported for secondary user
            launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(),
                    optsBundle);
        }
        return true;
    } catch (SecurityException e) {
        if (Utilities.ATLEAST_MARSHMALLOW && tag instanceof ItemInfo) {
            // Due to legacy reasons, direct call shortcuts require Launchers to have the
            // corresponding permission. Show the appropriate permission prompt if that
            // is the case.
            if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction())
                    && checkSelfPermission(
                            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Rename sPendingAddItem to a generic name.
                sPendingAddItem = preparePendingAddArgs(REQUEST_PERMISSION_CALL_PHONE, intent, 0,
                        (ItemInfo) tag);
                requestPermissions(new String[] { Manifest.permission.CALL_PHONE },
                        REQUEST_PERMISSION_CALL_PHONE);
                return false;
            }
        }
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Launcher does not have the permission to launch " + intent
                + ". Make sure to create a MAIN intent-filter for the corresponding activity "
                + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e);
    }
    return false;
}