Recursive binary search to find the best size for the text TextPaint. - Android Graphics

Android examples for Graphics:Paint

Description

Recursive binary search to find the best size for the text TextPaint.

Demo Code

/*//w  ww .  jav a2s  . c  o  m
 * Copyright 2015 Google Inc.
 *
 * 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.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.TypedValue;

public class Main {
  /**
   * Recursive binary search to find the best size for the text.
   *
   * Adapted from https://github.com/grantland/android-autofittextview
   */
  public static float getSingleLineTextSize(String text, TextPaint paint,
      float targetWidth, float low, float high, float precision,
      DisplayMetrics metrics) {
    final float mid = (low + high) / 2.0f;

    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,
        mid, metrics));
    final float maxLineWidth = paint.measureText(text);

    if ((high - low) < precision) {
      return low;
    } else if (maxLineWidth > targetWidth) {
      return getSingleLineTextSize(text, paint, targetWidth, low, mid,
          precision, metrics);
    } else if (maxLineWidth < targetWidth) {
      return getSingleLineTextSize(text, paint, targetWidth, mid, high,
          precision, metrics);
    } else {
      return mid;
    }
  }
}

Related Tutorials