get Text Font Scale X - Android Graphics

Android examples for Graphics:Font

Description

get Text Font Scale X

Demo Code

/*/*  w  ww.  j a va2 s .c  o m*/
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.StyleSpan;

public class Main {
  private static float getTextScaleX(final CharSequence text, final int maxWidth, final TextPaint paint) {
    paint.setTextScaleX(1.0f);
    final int width = getTextWidth(text, paint);
    if (width <= maxWidth) {
      return 1.0f;
    }
    return maxWidth / (float) width;
  }

  private static int getTextWidth(final CharSequence text, final TextPaint paint) {
    if (TextUtils.isEmpty(text)) {
      return 0;
    }
    final Typeface savedTypeface = paint.getTypeface();
    paint.setTypeface(getTextTypeface(text));
    final int len = text.length();
    final float[] widths = new float[len];
    final int count = paint.getTextWidths(text, 0, len, widths);
    int width = 0;
    for (int i = 0; i < count; i++) {
      width += Math.round(widths[i] + 0.5f);
    }
    paint.setTypeface(savedTypeface);
    return width;
  }

  private static Typeface getTextTypeface(final CharSequence text) {
    if (!(text instanceof SpannableString)) {
      return Typeface.DEFAULT;
    }

    final SpannableString ss = (SpannableString) text;
    final StyleSpan[] styles = ss.getSpans(0, text.length(), StyleSpan.class);
    if (styles.length == 0) {
      return Typeface.DEFAULT;
    }

    if (styles[0].getStyle() == Typeface.BOLD) {
      return Typeface.DEFAULT_BOLD;
    }
    // TODO: BOLD_ITALIC, ITALIC case?
    return Typeface.DEFAULT;
  }
}

Related Tutorials