TextPaint sub String Length - Android android.text

Android examples for android.text:TextPaint

Description

TextPaint sub String Length

Demo Code

/*/*from w  w  w. j a va2 s  .co m*/
 * Copyright (C) 2012 www.amsoft.cn
 * 
 * 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 java.util.ArrayList;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Paint.FontMetrics;
import android.text.Layout;
import android.text.TextPaint;

public class Main{
    
    public static int subStringLength(String str, int maxPix,
            TextPaint paint) {

        int currentIndex = 0;
        for (int i = 0; i < str.length(); i++) {

            String temp = str.substring(0, i + 1);
            float valueLength = paint.measureText(temp);
            if (valueLength > maxPix) {
                currentIndex = i - 1;
                break;
            } else if (valueLength == maxPix) {
                currentIndex = i;
                break;
            }
        }

        if (currentIndex == 0) {
            currentIndex = str.length() - 1;
        }
        return currentIndex;
    }
}

Related Tutorials