Example usage for android.graphics Paint measureText

List of usage examples for android.graphics Paint measureText

Introduction

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

Prototype

public float measureText(String text) 

Source Link

Document

Return the width of the text.

Usage

From source file:org.de.jmg.learn._MainActivity.java

void SetTxtStatusSize(int width) {
    if (width == 0)
        width = mainView.getWidth();/*from  w w  w .j a  v a 2s . co  m*/
    if (width == 0 && _OriginalWidth == 0)
        return;
    if (width == 0)
        width = _OriginalWidth;
    _OriginalWidth = width;
    TextView t = _txtStatus;
    Paint p = new Paint();
    if (t.getText() instanceof SpannedString) {
        p.setTextSize(t.getTextSize());
        SpannedString s = (SpannedString) t.getText();
        width = width - width / (_isSmallDevice ? 4 : 5);
        float measuredWidth = p.measureText(s.toString());
        if (measuredWidth != width) {
            float scaleA = (float) width / measuredWidth;
            if (libString.IsNullOrEmpty(_vok.getFileName()))
                scaleA *= .75f;
            if (scaleA < .5f)
                scaleA = .5f;
            if (scaleA > 2.0f)
                scaleA = 2.0f;
            float size = t.getTextSize();
            t.setTextSize(TypedValue.COMPLEX_UNIT_PX, size * scaleA);
        }

    }
}

From source file:fr.magistry.taigime.CandidateView.java

/**
 * If the canvas is null, then only touch calculations are performed to pick the target
 * candidate.// w w  w.java 2 s. c  o  m
 */
@Override
protected void onDraw(Canvas canvas) {
    if (canvas != null) {
        super.onDraw(canvas);
    }
    mTotalWidth = 0;
    if (mSuggestions == null)
        return;

    if (mBgPadding == null) {
        mBgPadding = new Rect(0, 0, 0, 0);
        if (getBackground() != null) {
            getBackground().getPadding(mBgPadding);
        }
    }
    int x = 0;
    final int count = mSuggestions.size();
    final int height = getHeight();
    final Rect bgPadding = mBgPadding;
    final Paint paint = mPaint;
    final int touchX = mTouchX;
    final int scrollX = getScrollX();
    final boolean scrolled = mScrolled;
    final int y; //= (int) ( - mPaint.ascent() + mVerticalPadding);
    final int y2; //= (int) (height - mPaintTRS.descent()); // (y - mVerticalPadding - mPaint.descent() - mPaintTRS.ascent()) ;
    final float initialTRSsize = mPaintTRS.getTextSize();
    if (mOutputTRS) {
        y2 = (int) (-mPaintTRS.ascent() + mVerticalPadding);
        y = (int) (height - mPaint.descent());

    } else {
        y = (int) (-mPaint.ascent() + mVerticalPadding);
        y2 = (int) (height - mPaintTRS.descent());

    }
    for (int i = 0; i < count; i++) {
        Candidate suggestion = mSuggestions.get(i);
        String hanji = suggestion.getWord().getHanji();
        String trs = "";
        switch (ROMANISATION_OUTPUT_MODE) {
        case 0:
            trs = suggestion.getWord().getTailuo();
            break;
        case 1:
            trs = suggestion.getWord().getPOJ();
            break;
        case 2:
            trs = suggestion.getWord().getPOJ_safe();
            break;
        default:
            trs = suggestion.getWord().getTailuo();
        }
        float textWidth;
        if (i == 0) {
            hanji = "";
            trs = "";//hanji;//TODO: conversion?
            //if(mOutputTRS){
            trs = suggestion.getWord().getBopomo();
            if (trs != "")
                textWidth = mPaintBPM.measureText(trs);
            else
                textWidth = 3;
            //}
            //else {
            //   hanji = suggestion.getWord().getBopomo();
            //   textWidth = paint.measureText(hanji);
            //}
        } else
            textWidth = paint.measureText(hanji);
        if (textWidth == 0.0)
            textWidth = paint.measureText(" ");

        final int wordWidth = (int) textWidth + X_GAP * 2;
        mWordX[i] = x;
        mWordWidth[i] = wordWidth;
        mPaintTRS.setTextSize(initialTRSsize);
        mPaintTRS.setTextSize(reduceTextSizeFromWidth(mPaintTRS, trs, textWidth));
        paint.setColor(mColorNormal);
        if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) {
            if (canvas != null) {
                canvas.translate(x, 0);
                mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
                mSelectionHighlight.draw(canvas);
                canvas.translate(-x, 0);
            }
            mSelectedIndex = i;
        }

        if (canvas != null) {
            Paint activePaint = null;
            Paint secondPaint = null;
            if (mOutputTRS) {
                activePaint = mPaintTRS;
                secondPaint = paint;
            } else {
                activePaint = paint;
                secondPaint = mPaintTRS;
            }
            if (i == 0) {
                activePaint = mPaintBPM;
            }
            secondPaint.setAlpha(150);
            if ((i == mCursor)) {
                activePaint.setFakeBoldText(true);
                activePaint.setColor(mColorRecommended);
            } else if (i != 0) {
                activePaint.setColor(mColorOther);
            }
            if (i == 0) {
                canvas.drawText(trs, x + X_GAP, y2, mPaintBPM);
            } else {
                canvas.drawText(hanji, x + X_GAP, y, paint);
                canvas.drawText(trs, x + X_GAP, y2, mPaintTRS);
            }
            activePaint.setColor(mColorOther);
            canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, x + wordWidth + 0.5f, height + 1, paint);
            activePaint.setFakeBoldText(false);
            secondPaint.setAlpha(255);
        }
        x += wordWidth;
        mPaintTRS.setTextSize(initialTRSsize);
    }
    mTotalWidth = x;
    if (mTargetScrollX != getScrollX()) {
        scrollToTarget();
    }
}

From source file:com.almalence.opencam.SavingService.java

protected void drawTextWithBackground(Canvas canvas, Paint paint, String text, int foreground, int background,
        int imageWidth, int imageHeight) {
    Rect text_bounds = new Rect();
    paint.setColor(foreground);/*from  w  ww .j  a v  a2  s.c  o m*/
    String[] resText = text.split("\n");
    String maxLengthText = "";

    if (resText.length > 1) {
        maxLengthText = resText[0].length() > resText[1].length() ? resText[0] : resText[1];
    } else if (resText.length > 0) {
        maxLengthText = resText[0];
    }

    final float scale = getResources().getDisplayMetrics().density;
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(background);
    paint.setAlpha(64);
    paint.getTextBounds(text, 0, maxLengthText.length(), text_bounds);
    final int padding = (int) (2 * scale + 0.5f); // convert dps to pixels

    int textWidth = 0;
    int textHeight = text_bounds.bottom - text_bounds.top;
    if (paint.getTextAlign() == Paint.Align.RIGHT || paint.getTextAlign() == Paint.Align.CENTER) {
        float width = paint.measureText(maxLengthText); // n.b., need to use
        // measureText
        // rather than
        // getTextBounds
        // here
        textWidth = (int) width;
    }

    text_bounds.left = imageWidth - textWidth - resText.length * padding;
    text_bounds.right = imageWidth - padding;
    if (resText.length > 1) {
        text_bounds.top = imageHeight - resText.length * padding - resText.length * textHeight - textHeight;
    } else {
        text_bounds.top = imageHeight - 2 * padding - textHeight;
        textHeight /= 3;
    }
    text_bounds.bottom = imageHeight - padding;

    paint.setColor(foreground);
    if (resText.length > 0) {
        canvas.drawText(resText[0], imageWidth - 5 * padding,
                imageHeight - resText.length * textHeight - textHeight / 2, paint);
    }
    if (resText.length > 1) {
        canvas.drawText(resText[1], imageWidth - 5 * padding, imageHeight - (resText.length - 1) * textHeight,
                paint);
    }
    if (resText.length > 2) {
        canvas.drawText(resText[2], imageWidth - 5 * padding,
                imageHeight - (resText.length - 2) * textHeight + textHeight / 2, paint);
    }
    if (resText.length > 3) {
        canvas.drawText(resText[3], imageWidth - 5 * padding, imageHeight - textHeight / 4, paint);
    }
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    int userId = Util.getUserId(Process.myUid());
    boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    boolean updates = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingUpdates, false);

    menu.findItem(R.id.menu_export).setEnabled(mounted);
    menu.findItem(R.id.menu_import).setEnabled(mounted);

    menu.findItem(R.id.menu_submit).setEnabled(Util.hasValidFingerPrint(this));

    menu.findItem(R.id.menu_pro).setVisible(!Util.isProEnabled() && Util.hasProLicense(this) == null);

    menu.findItem(R.id.menu_dump).setVisible(Util.isDebuggable(this));

    menu.findItem(R.id.menu_update).setVisible(updates);
    menu.findItem(R.id.menu_update).setEnabled(mounted);

    // Update filter count

    // Get settings
    boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false);
    boolean fInternet = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFInternet, false);
    boolean fRestriction = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestriction, false);
    boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, true);
    boolean fOnDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemand, false);
    boolean fUser = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUser, true);
    boolean fSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFSystem, false);

    // Count number of active filters
    int numberOfFilters = 0;
    if (fUsed)/*from  ww  w . j  a  va  2  s.  c  o m*/
        numberOfFilters++;
    if (fInternet)
        numberOfFilters++;
    if (fRestriction)
        numberOfFilters++;
    if (fPermission)
        numberOfFilters++;
    if (fOnDemand)
        numberOfFilters++;
    if (fUser)
        numberOfFilters++;
    if (fSystem)
        numberOfFilters++;

    if (numberOfFilters > 0) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_filter)
                .copy(Bitmap.Config.ARGB_8888, true);

        Paint paint = new Paint();
        paint.setStyle(Style.FILL);
        paint.setColor(Color.GRAY);
        paint.setTextSize(bitmap.getWidth() / 3);
        paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

        String text = Integer.toString(numberOfFilters);

        Canvas canvas = new Canvas(bitmap);
        canvas.drawText(text, bitmap.getWidth() - paint.measureText(text), bitmap.getHeight(), paint);

        MenuItem fMenu = menu.findItem(R.id.menu_filter);
        fMenu.setIcon(new BitmapDrawable(getResources(), bitmap));
    }

    return super.onPrepareOptionsMenu(menu);
}

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

private int computeMaxStringWidth(int currentMax, String[] strings, Paint p) {
    float maxWidthF = 0.0f;

    int len = strings.length;
    for (int i = 0; i < len; i++) {
        float width = p.measureText(strings[i]);
        maxWidthF = Math.max(width, maxWidthF);
    }//w w w .j ava 2 s.  c o m
    int maxWidth = (int) (maxWidthF + 0.5);
    if (maxWidth < currentMax) {
        maxWidth = currentMax;
    }
    return maxWidth;
}

From source file:net.toload.main.hd.candidate.CandidateView.java

private void doDraw(Canvas canvas) {

    if (mSuggestions == null)
        return;/*from   w ww  .j av  a2s  .c o  m*/
    if (DEBUG)
        Log.i(TAG, "CandidateView:doDraw():Suggestion mCount:" + mCount + " mSuggestions.size:"
                + mSuggestions.size());
    mTotalWidth = 0;

    updateFontSize();

    if (mBgPadding == null) {
        mBgPadding = new Rect(0, 0, 0, 0);
        if (getBackground() != null) {
            getBackground().getPadding(mBgPadding);
        }
    }

    final int height = mHeight;
    final Rect bgPadding = mBgPadding;
    final Paint candidatePaint = mCandidatePaint;
    final Paint candidateEmojiPaint = mCandidatePaint;
    candidateEmojiPaint.setTextSize((float) (candidateEmojiPaint.getTextSize() * 0.9));

    final Paint selKeyPaint = mSelKeyPaint;
    final int touchX = mTouchX;
    final int scrollX = getScrollX();
    final boolean scrolled = mScrolled;

    final int textBaseLine = (int) (((height - mCandidatePaint.getTextSize()) / 2) - mCandidatePaint.ascent());

    // Modified by jeremy '10, 3, 29.  Update mselectedindex if touched and build wordX[i] and wordwidth[i]
    int x = 0;
    final int count = mCount; //Cache count here '11,8,18
    for (int i = 0; i < count; i++) {
        if (count != mCount || mSuggestions == null || count != mSuggestions.size() || mSuggestions.size() == 0
                || i >= mSuggestions.size())
            return; // mSuggestion is updated, force abort

        String suggestion = mSuggestions.get(i).getWord();
        if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord()
                && suggestion.length() > 8) {
            suggestion = suggestion.substring(0, 2) + "..";
        }
        float base = (suggestion == null) ? 0 : candidatePaint.measureText("");
        float textWidth = (suggestion == null) ? 0 : candidatePaint.measureText(suggestion);

        if (textWidth < base) {
            textWidth = base;
        }

        final int wordWidth = (int) textWidth + X_GAP * 2;

        mWordX[i] = x;

        mWordWidth[i] = wordWidth;

        if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) {
            mSelectedIndex = i;
        }
        x += wordWidth;
    }

    mTotalWidth = x;

    if (DEBUG)
        Log.i(TAG,
                "CandidateView:doDraw():mTotalWidth :" + mTotalWidth + "  this.getWidth():" + this.getWidth());

    //Jeremy '11,8,11. If the candidate list is within 1 page and has more records, get full records first.
    if (mTotalWidth < this.getWidth())
        checkHasMoreRecords();

    // Paint all the suggestions and lines.
    if (canvas != null) {

        // Moved from above by jeremy '10 3, 29. Paint mSelectedindex in highlight here
        if (count > 0 && mSelectedIndex >= 0) {
            //    candidatePaint.setColor(mColorComposingCode);
            //    canvas.drawRect(mWordX[mSelectedIndex],bgPadding.top, mWordWidth[mSelectedIndex] , height, candidatePaint);

            canvas.translate(mWordX[mSelectedIndex], 0);
            mDrawableSuggestHighlight.setBounds(0, bgPadding.top, mWordWidth[mSelectedIndex], height);
            mDrawableSuggestHighlight.draw(canvas);
            canvas.translate(-mWordX[mSelectedIndex], 0);

        }
        if (mTransparentCandidateView) {
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

            Paint backgroundPaint = new Paint();
            backgroundPaint.setColor(ContextCompat.getColor(mContext, R.color.third_background_light));
            backgroundPaint.setAlpha(33);
            backgroundPaint.setStyle(Paint.Style.FILL);

            canvas.drawRect(0.5f, bgPadding.top, mScreenWidth, height, backgroundPaint);
        }

        for (int i = 0; i < count; i++) {

            if (count != mCount || mSuggestions == null || count != mSuggestions.size()
                    || mSuggestions.size() == 0 || i >= mSuggestions.size())
                break;

            boolean isEmoji = mSuggestions.get(i).isEmojiRecord();
            String suggestion = mSuggestions.get(i).getWord();
            if (i == 0 && mSuggestions.size() > 1 && mSuggestions.get(1).isRuntimeBuiltPhraseRecord()
                    && suggestion.length() > 8) {
                suggestion = suggestion.substring(0, 2) + "..";
            }

            int c = i + 1;
            switch (mSuggestions.get(i).getRecordType()) {
            case Mapping.RECORD_COMPOSING_CODE:
                if (mSelectedIndex == 0) {

                    if (mTransparentCandidateView) {
                        candidatePaint.setColor(mColorInvertedTextTransparent);
                    } else {
                        candidatePaint.setColor(mColorComposingCodeHighlight);
                    }
                } else
                    candidatePaint.setColor(mColorComposingCode);
                break;
            case Mapping.RECORD_CHINESE_PUNCTUATION_SYMBOL:
            case Mapping.RECORD_RELATED_PHRASE:
                selKeyPaint.setColor(mColorSelKeyShifted);
                if (i == mSelectedIndex)
                    candidatePaint.setColor(mColorNormalTextHighlight);
                else
                    candidatePaint.setColor(mColorNormalText);
                break;
            case Mapping.RECORD_EXACT_MATCH_TO_CODE:
            case Mapping.RECORD_PARTIAL_MATCH_TO_CODE:
            case Mapping.RECORD_RUNTIME_BUILT_PHRASE:
            case Mapping.RECORD_ENGLISH_SUGGESTION:
            default:
                selKeyPaint.setColor(mColorSelKey);
                if (i == mSelectedIndex)
                    candidatePaint.setColor(mColorNormalTextHighlight);
                else
                    candidatePaint.setColor(mColorNormalText);
                break;

            }

            if (isEmoji) {
                canvas.drawText(suggestion, mWordX[i] + X_GAP, Math.round(textBaseLine * 0.95),
                        candidateEmojiPaint);
            } else {
                canvas.drawText(suggestion, mWordX[i] + X_GAP, textBaseLine, candidatePaint);
            }
            if (mShowNumber) {
                //Jeremy '11,6,17 changed from <=10 to mDisplaySelkey length. The length maybe 11 or 12 if shifted with space.
                if (c <= mDisplaySelkey.length()) {
                    //Jeremy '11,6,11 Drawing text using relative font dimensions.
                    canvas.drawText(mDisplaySelkey.substring(c - 1, c),
                            mWordX[i] + mWordWidth[i] - height * 0.3f, height * 0.4f, selKeyPaint);
                }
            }
            //Draw spacer
            candidatePaint.setColor(mColorSpacer);
            canvas.drawLine(mWordX[i] + mWordWidth[i] + 0.5f, bgPadding.top + (mVerticalPadding / 2),
                    mWordX[i] + mWordWidth[i] + 0.5f, height - (mVerticalPadding / 2), candidatePaint);
            candidatePaint.setFakeBoldText(false);

        }

        if (mTargetScrollX != getScrollX()) {
            if (DEBUG)
                Log.i(TAG, "CandidateView:doDraw():mTargetScrollX :" + mTargetScrollX + "  getScrollX():"
                        + getScrollX());
            scrollToTarget();
        }

    }

}

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

private void drawDayHeader(String dayStr, int day, String dateNumStr, Canvas canvas, Paint p) {
    int x;//  ww  w  .j  a v  a 2s  .c o  m
    p.setAntiAlias(true);

    int todayIndex = mTodayJulianDay - mFirstJulianDay;
    // Draw day of the month
    if (mNumDays > 1) {
        float y = DAY_HEADER_HEIGHT - DAY_HEADER_BOTTOM_MARGIN;

        // Draw day of the month
        x = computeDayLeftPosition(day + 1) - DAY_HEADER_RIGHT_MARGIN;
        p.setTextAlign(Align.RIGHT);
        p.setTextSize(DATE_HEADER_FONT_SIZE);

        p.setTypeface(todayIndex == day ? mBold : Typeface.DEFAULT);
        canvas.drawText(dateNumStr, x, y, p);

        // Draw day of the week
        x -= p.measureText(" " + dateNumStr);
        p.setTextSize(DAY_HEADER_FONT_SIZE);
        p.setTypeface(Typeface.DEFAULT);
        canvas.drawText(dayStr, x, y, p);
    } else {
        float y = DAY_HEADER_HEIGHT - DAY_HEADER_ONE_DAY_BOTTOM_MARGIN;
        p.setTextAlign(Align.LEFT);

        // Draw day of the week
        x = computeDayLeftPosition(day) + DAY_HEADER_ONE_DAY_LEFT_MARGIN;
        x = x + ((mCellWidth - mDateStrWidthLong) / 2);
        p.setTextSize(DAY_HEADER_FONT_SIZE);
        p.setTypeface(Typeface.DEFAULT);
        canvas.drawText(dayStr, x, y, p);

        // Draw day of the month
        x += p.measureText(dayStr) + DAY_HEADER_ONE_DAY_RIGHT_MARGIN;
        p.setTextSize(DATE_HEADER_FONT_SIZE);
        p.setTypeface(todayIndex == day ? mBold : Typeface.DEFAULT);
        canvas.drawText(dateNumStr, x, y, p);
    }
}

From source file:com.zoffcc.applications.zanavi.Navit.java

synchronized static int find_max_letters_for_width_and_fontsize(String max_length_text, int width,
        int max_font_size, int padding_in_dp) {
    int ret_max_letters = 10;

    int padding_in_px = 0;
    if (padding_in_dp > 0) {
        //System.out.println("aaa2:l:1:x:" + padding_in_dp);
        padding_in_px = NavitGraphics.dp_to_px(padding_in_dp);
        //System.out.println("aaa2:l:1:x:2=" + padding_in_dp + " " + padding_in_px + " " + NavitGraphics.dp_to_px(padding_in_dp) + " " + NavitGraphics.Global_dpi_factor_better);
    }//from www. jav a 2  s .co  m
    //System.out.println("aaa2:l:1:x:1=" + padding_in_px);

    int c = 0;
    Paint p = new Paint();
    p.setTextSize(max_font_size);

    String s = max_length_text;

    if ((s == null) || (s.equals(""))) {
        s = "Mlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwoMlox3miwo";
    }

    int l = s.length();
    ret_max_letters = l;
    float mt = p.measureText(s);
    //System.out.println("aaa2:l:1:" + l + " " + s);
    //System.out.println("aaa2:l:22:." + mt + " padding_in_px=" + padding_in_px + " " + width);

    while (mt + padding_in_px > width) {
        //System.out.println("aaa2:l:22:+" + mt + " " + padding_in_px + " " + width);

        c++;
        if (c == l) {
            // no more letters
            //System.out.println("aaa2:l:1:no more letters:" + l + " " + s);
            break;
        }
        s = s.substring(0, s.length() - 1);
        mt = p.measureText(s);
        ret_max_letters--;
    }

    //System.out.println("aaa2:l:1:res=" + ret_max_letters);
    return ret_max_letters;
}