Java Code Examples for android.graphics.Paint#measureText()

The following examples show how to use android.graphics.Paint#measureText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NumberSpan.java    From memoir with Apache License 2.0 6 votes vote down vote up
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                              CharSequence text, int start, int end, boolean first, Layout l) {

    Spanned spanned = (Spanned) text;
    if (!mIgnoreSpan && spanned.getSpanStart(this) == start) {
        // set paint
        Paint.Style oldStyle = p.getStyle();
        float oldTextSize = p.getTextSize();
        p.setStyle(Paint.Style.FILL);
        mTextSize = baseline - top;
        p.setTextSize(mTextSize);
        mWidth = p.measureText(mNr + ".");

        // draw the number
        c.drawText(mNr + ".", x, baseline, p);

        // restore paint
        p.setStyle(oldStyle);
        p.setTextSize(oldTextSize);
    }
}
 
Example 2
Source File: CustomLabelSpan.java    From SimplifySpan with MIT License 6 votes vote down vote up
private float initFinalWidth(Paint paint) {
    if (mFinalWidth <= 0) {
        float labelTextSize = mSpecialLabelUnit.getLabelTextSize();
        if (labelTextSize > 0 && labelTextSize != paint.getTextSize()) {
            paint.setTextSize(labelTextSize);
        }

        int labelBgWidth = mSpecialLabelUnit.getLabelBgWidth();
        mSpecialTextWidth = paint.measureText(mSpecialText, 0, mSpecialText.length());
        if (labelBgWidth > 0 && labelBgWidth > mSpecialTextWidth) {
            mFinalWidth = labelBgWidth;
        } else {
            mFinalWidth = mSpecialTextWidth + mPaddingLeft + mPaddingRight;
        }
    }

    return mFinalWidth;
}
 
Example 3
Source File: AutoSplitTextView.java    From SprintNBA with Apache License 2.0 5 votes vote down vote up
@NonNull
private String autoSplitText(final TextView tv) {
    final String rawText = tv.getText().toString(); //原始文本
    final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息
    final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度
    
    //将原始文本按行拆分
    String [] rawTextLines = rawText.replaceAll("\r", "").split("\n");
    StringBuilder sbNewText = new StringBuilder();
    for (String rawTextLine : rawTextLines) {
        if (tvPaint.measureText(rawTextLine) <= tvWidth) {
            //如果整行宽度在控件可用宽度之内,就不处理了
            sbNewText.append(rawTextLine);
        } else {
            //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行
            float lineWidth = 0;
            for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                char ch = rawTextLine.charAt(cnt);
                lineWidth += tvPaint.measureText(String.valueOf(ch));
                if (lineWidth <= tvWidth) {
                    sbNewText.append(ch);
                } else {
                    sbNewText.append("\n");
                    lineWidth = 0;
                    --cnt;
                }
            }
        }
        sbNewText.append("\n");
    }
    
    //把结尾多余的\n去掉
    if (!rawText.endsWith("\n")) {
        sbNewText.deleteCharAt(sbNewText.length() - 1);
    }
    
    return sbNewText.toString();
}
 
Example 4
Source File: LocationsSwipeController.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private void drawText(String text, Canvas c, RectF button, Paint p) {
    float textSize = 60;
    p.setColor(Color.WHITE);
    p.setAntiAlias(true);
    p.setTextSize(textSize);

    float textWidth = p.measureText(text);
    c.drawText(text, button.centerX()-(textWidth/2), button.centerY()+(textSize/2), p);
}
 
Example 5
Source File: HollowTextActivity.java    From android-graphics-demo with Apache License 2.0 5 votes vote down vote up
@Override
public int getSize(
    Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
  this.paint.setColor(paint.getColor());

  width = (int) (paint.measureText(text, start, end) + this.paint.getStrokeWidth());
  return width;
}
 
Example 6
Source File: SlashSpan.java    From android-card-form with MIT License 5 votes vote down vote up
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
    float padding = paint.measureText(" ", 0, 1) * 2;
    float slash = paint.measureText("/", 0, 1);
    float textSize = paint.measureText(text, start, end);
    return (int) (padding + slash + textSize);
}
 
Example 7
Source File: TitlePageIndicator.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the bounds for a view's title
 *
 * @param index
 * @param paint
 * @return
 */
private Rect calcBounds(int index, Paint paint) {
    //Calculate the text bounds
    Rect bounds = new Rect();
    CharSequence title = getTitle(index);
    bounds.right = (int) paint.measureText(title, 0, title.length());
    bounds.bottom = (int) (paint.descent() - paint.ascent());
    return bounds;
}
 
Example 8
Source File: AlignTextView.java    From AlignTextView with Apache License 2.0 5 votes vote down vote up
/**
 * 计算每行应显示的文本数
 *
 * @param text 要计算的文本
 */
private void calc(Paint paint, String text) {
    if (text.length() == 0) {
        lines.add("\n");
        return;
    }
    int startPosition = 0; // 起始位置
    float oneChineseWidth = paint.measureText("中");
    int ignoreCalcLength = (int) (width / oneChineseWidth); // 忽略计算的长度
    StringBuilder sb = new StringBuilder(text.substring(0, Math.min(ignoreCalcLength + 1,
            text.length())));

    for (int i = ignoreCalcLength + 1; i < text.length(); i++) {
        if (paint.measureText(text.substring(startPosition, i + 1)) > width) {
            startPosition = i;
            //将之前的字符串加入列表中
            lines.add(sb.toString());

            sb = new StringBuilder();

            //添加开始忽略的字符串,长度不足的话直接结束,否则继续
            if ((text.length() - startPosition) > ignoreCalcLength) {
                sb.append(text.substring(startPosition, startPosition + ignoreCalcLength));
            } else {
                lines.add(text.substring(startPosition));
                break;
            }

            i = i + ignoreCalcLength - 1;
        } else {
            sb.append(text.charAt(i));
        }
    }
    if (sb.length() > 0) {
        lines.add(sb.toString());
    }

    tailLines.add(lines.size() - 1);
}
 
Example 9
Source File: TitlePageIndicator.java    From Klyph with MIT License 5 votes vote down vote up
/**
 * Calculate the bounds for a view's title
 *
 * @param index
 * @param paint
 * @return
 */
private Rect calcBounds(int index, Paint paint) {
    //Calculate the text bounds
    Rect bounds = new Rect();
    CharSequence title = getTitle(index);
    bounds.right = (int) paint.measureText(title, 0, title.length());
    bounds.bottom = (int) (paint.descent() - paint.ascent());
    return bounds;
}
 
Example 10
Source File: CompassView.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
public CompassView(Context context, AttributeSet attrs,
                   int defStyleAttr) {
  super(context, attrs, defStyleAttr);

  setFocusable(true);
  final TypedArray a = context.obtainStyledAttributes(attrs,
    R.styleable.CompassView, defStyleAttr, 0);
  if (a.hasValue(R.styleable.CompassView_bearing)) {
    setBearing(a.getFloat(R.styleable.CompassView_bearing, 0));
  }
  a.recycle();

  Context c = this.getContext();
  Resources r = this.getResources();

  circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  circlePaint.setColor(ContextCompat.getColor(c, R.color.background_color));
  circlePaint.setStrokeWidth(1);
  circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
  circlePaint.setStyle(Paint.Style.STROKE);

  northString = r.getString(R.string.cardinal_north);
  eastString = r.getString(R.string.cardinal_east);
  southString = r.getString(R.string.cardinal_south);
  westString = r.getString(R.string.cardinal_west);

  textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  textPaint.setColor(ContextCompat.getColor(c, R.color.text_color));
  textPaint.setTextSize(40);
  textPaint.setFakeBoldText(true);
  textPaint.setSubpixelText(true);
  textPaint.setTextAlign(Paint.Align.LEFT);
  textPaint.setTextSize(30);

  textHeight = (int)textPaint.measureText("yY");

  markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  markerPaint.setColor(ContextCompat.getColor(c, R.color.marker_color));
  markerPaint.setAlpha(200);
  markerPaint.setStrokeWidth(1);
  markerPaint.setStyle(Paint.Style.STROKE);
  markerPaint.setShadowLayer(2, 1, 1, ContextCompat.getColor(c,
    R.color.shadow_color));

  borderGradientColors = new int[4];
  borderGradientPositions = new float[4];
  borderGradientColors[3] = ContextCompat.getColor(c,
    R.color.outer_border);
  borderGradientColors[2] = ContextCompat.getColor(c,
    R.color.inner_border_one);
  borderGradientColors[1] = ContextCompat.getColor(c,
    R.color.inner_border_two);
  borderGradientColors[0] = ContextCompat.getColor(c,
    R.color.inner_border);
  borderGradientPositions[3] = 0.0f;
  borderGradientPositions[2] = 1-0.03f;
  borderGradientPositions[1] = 1-0.06f;
  borderGradientPositions[0] = 1.0f;

  glassGradientColors = new int[5];
  glassGradientPositions = new float[5];

  int glassColor = 245;
  glassGradientColors[4] = Color.argb(65, glassColor,
    glassColor, glassColor);
  glassGradientColors[3] = Color.argb(100, glassColor,
    glassColor, glassColor);
  glassGradientColors[2] = Color.argb(50, glassColor,
    glassColor, glassColor);
  glassGradientColors[1] = Color.argb(0, glassColor,
    glassColor, glassColor);
  glassGradientColors[0] = Color.argb(0, glassColor,
    glassColor, glassColor);
  glassGradientPositions[4] = 1-0.0f;
  glassGradientPositions[3] = 1-0.06f;
  glassGradientPositions[2] = 1-0.10f;
  glassGradientPositions[1] = 1-0.20f;
  glassGradientPositions[0] = 1-1.0f;

  skyHorizonColorFrom = ContextCompat.getColor(c,
    R.color.horizon_sky_from);
  skyHorizonColorTo = ContextCompat.getColor(c,
    R.color.horizon_sky_to);
  groundHorizonColorFrom = ContextCompat.getColor(c,
    R.color.horizon_ground_from);
  groundHorizonColorTo = ContextCompat.getColor(c,
    R.color.horizon_ground_to);
}
 
Example 11
Source File: BezierCurveChart.java    From android-bezier-curve-chart with Apache License 2.0 4 votes vote down vote up
public float getTextWidth(Paint textPaint, String text) {
	return textPaint.measureText(text);
}
 
Example 12
Source File: BadgeHelper.java    From imsdk-android with MIT License 4 votes vote down vote up
private float getTextWidth(String text, Paint p) {
    return p.measureText(text, 0, text.length());
}
 
Example 13
Source File: SmallAnimatedTextView.java    From tilt-game-android with MIT License 4 votes vote down vote up
@Override
		public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
			int size = (int) paint.measureText(text, start, end);
//			Log.d(TAG, "text: " + text + ", letter: " + text.charAt(start) + "size: " + size);
			return size;
		}
 
Example 14
Source File: NumberPickerView.java    From SmartChart with Apache License 2.0 4 votes vote down vote up
private int getTextWidth(CharSequence text, Paint paint){
    if(!TextUtils.isEmpty(text)){
        return (int)(paint.measureText(text.toString()) + 0.5f);
    }
    return 0;
}
 
Example 15
Source File: AnalyzerViews.java    From audio-analyzer-for-android with Apache License 2.0 4 votes vote down vote up
private PopupWindow popupMenuCreate(String[] popUpContents, int resId) {

        // initialize a pop up window type
        PopupWindow popupWindow = new PopupWindow(activity);

        // the drop down list is a list view
        ListView listView = new ListView(activity);

        // set our adapter and pass our pop up window contents
        ArrayAdapter<String> aa = popupMenuAdapter(popUpContents);
        listView.setAdapter(aa);

        // set the item click listener
        listView.setOnItemClickListener(activity);

        // button resource ID, so we can trace back which button is pressed
        listView.setTag(resId);

        // get max text width
        Paint mTestPaint = new Paint();
        mTestPaint.setTextSize(listItemTextSize);
        float w = 0;  // max text width in pixel
        float wi;
        for (String popUpContent : popUpContents) {
            String sts[] = popUpContent.split("::");
            if (sts.length == 0) continue;
            String st = sts[0];
            if (sts.length == 2 && sts[1].equals("0")) {
                mTestPaint.setTextSize(listItemTitleTextSize);
                wi = mTestPaint.measureText(st);
                mTestPaint.setTextSize(listItemTextSize);
            } else {
                wi = mTestPaint.measureText(st);
            }
            if (w < wi) {
                w = wi;
            }
        }

        // left and right padding, at least +7, or the whole app will stop respond, don't know why
        w = w + 23 * DPRatio;
        if (w < 40 * DPRatio) {
            w = 40 * DPRatio;
        }

        // some other visual settings
        popupWindow.setFocusable(true);
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        // Set window width according to max text width
        popupWindow.setWidth((int)w);
        // also set button width
        ((Button) activity.findViewById(resId)).setWidth((int)(w + 5 * DPRatio));
        // Set the text on button in loadPreferenceForView()

        // set the list view as pop up window content
        popupWindow.setContentView(listView);

        return popupWindow;
    }
 
Example 16
Source File: TabRadioButton.java    From TabRadioButton with Apache License 2.0 4 votes vote down vote up
private float getFontWidth(Paint paint, String text) {
    return paint.measureText(text);
}
 
Example 17
Source File: SmileRating.java    From SmileyRating with Apache License 2.0 4 votes vote down vote up
private void drawTextCentered(String text, float x, float y, Paint paint, Canvas canvas) {
    float xPos = x - (paint.measureText(text) / 2);
    float yPos = (y - ((paint.descent() + paint.ascent()) / 2));

    canvas.drawText(text, xPos, yPos, paint);
}
 
Example 18
Source File: IndexFastScrollRecyclerSection.java    From 920-text-editor-v2 with Apache License 2.0 4 votes vote down vote up
public void draw(Canvas canvas) {
    Paint indexbarPaint = new Paint();
    indexbarPaint.setColor(Color.parseColor(indexbarBackgroudColor));
    indexbarPaint.setAlpha(indexbarBackgroudAlpha);
    indexbarPaint.setAntiAlias(true);
    canvas.drawRoundRect(mIndexbarRect, setIndexBarCornerRadius * mDensity, setIndexBarCornerRadius * mDensity, indexbarPaint);

    if (mSections != null && mSections.length > 0) {
        // Preview is shown when mCurrentSection is set
        if (mCurrentSection >= 0) {
            Paint previewPaint = new Paint();
            previewPaint.setColor(Color.BLACK);
            previewPaint.setAlpha(96);
            previewPaint.setAntiAlias(true);
            previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));

            Paint previewTextPaint = new Paint();
            previewTextPaint.setColor(Color.WHITE);
            previewTextPaint.setAntiAlias(true);
            previewTextPaint.setTextSize(50 * mScaledDensity);
            previewTextPaint.setTypeface(setTypeface);

            float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
            float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
            RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
                    , (mListViewHeight - previewSize) / 2
                    , (mListViewWidth - previewSize) / 2 + previewSize
                    , (mListViewHeight - previewSize) / 2 + previewSize);

            canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
            canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
                    , previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
            fade(300);
        }

        Paint indexPaint = new Paint();
        indexPaint.setColor(Color.parseColor(indexbarTextColor));
        indexPaint.setAntiAlias(true);
        indexPaint.setTextSize(setIndexTextSize * mScaledDensity);
        indexPaint.setTypeface(setTypeface);

        float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
        float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
        for (int i = 0; i < mSections.length; i++) {
            float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
            canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
                    , mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
        }
    }
}
 
Example 19
Source File: ProfitsChartView.java    From ClockView with Apache License 2.0 4 votes vote down vote up
public float getFontWidth(Paint paint, String text) {
    return paint.measureText(text);
}
 
Example 20
Source File: SinglePointRenderer.java    From mil-sym-android with Apache License 2.0 4 votes vote down vote up
public Bitmap getTestSymbol()
 {
     Bitmap temp = null;
     try
     {
         temp = Bitmap.createBitmap(70, 70, Config.ARGB_8888);

         Canvas canvas = new Canvas(temp);

         if (canvas.isHardwareAccelerated())
         {
             System.out.println("HW acceleration supported");
         }
//canvas.drawColor(Color.WHITE);

         //Typeface tf = Typeface.createFromAsset(_am, "fonts/unitfonts.ttf");
         Typeface tf = _tfUnits;

         Paint fillPaint = new Paint();
         fillPaint.setStyle(Paint.Style.FILL);
         fillPaint.setColor(Color.CYAN.toInt());
         fillPaint.setTextSize(50);
         fillPaint.setAntiAlias(true);
         fillPaint.setTextAlign(Align.CENTER);
         fillPaint.setTypeface(tf);

         Paint framePaint = new Paint();
         framePaint.setStyle(Paint.Style.FILL);
         framePaint.setColor(Color.BLACK.toInt());
         framePaint.setTextSize(50);
         framePaint.setAntiAlias(true);
         framePaint.setTextAlign(Align.CENTER);
         framePaint.setTypeface(tf);

         Paint symbolPaint = new Paint();
         symbolPaint.setStyle(Paint.Style.FILL);
         symbolPaint.setColor(Color.BLACK.toInt());
         symbolPaint.setTextSize(50);
         symbolPaint.setAntiAlias(true);
         symbolPaint.setTextAlign(Align.CENTER);
         symbolPaint.setTypeface(tf);

         String strFill = String.valueOf((char) 800);
         String strFrame = String.valueOf((char) 801);
         String strSymbol = String.valueOf((char) 1121);

         canvas.drawText(strFill, 35, 35, fillPaint);
         canvas.drawText(strFrame, 35, 35, framePaint);
         canvas.drawText(strSymbol, 35, 35, symbolPaint);

         FontMetrics mf = framePaint.getFontMetrics();
         float height = mf.bottom - mf.top;
         float width = fillPaint.measureText(strFrame);

         Log.i(TAG, "top: " + String.valueOf(mf.top));
         Log.i(TAG, "bottom: " + String.valueOf(mf.bottom));
         Log.i(TAG, "ascent: " + String.valueOf(mf.ascent));
         Log.i(TAG, "descent: " + String.valueOf(mf.descent));
         Log.i(TAG, "leading: " + String.valueOf(mf.leading));
         Log.i(TAG, "width: " + String.valueOf(width));
         Log.i(TAG, "height: " + String.valueOf(height));

     }
     catch (Exception exc)
     {
         Log.e(TAG, exc.getMessage());
         Log.e(TAG, getStackTrace(exc));
     }

     return temp;
 }