StyleSpan.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.text.style;
18
19import android.graphics.Paint;
20import android.graphics.Typeface;
21import android.text.TextPaint;
22
23/**
24 *
25 * Describes a style in a span.
26 * Note that styles are cumulative -- if both bold and italic are set in
27 * separate spans, or if the base style is bold and a span calls for italic,
28 * you get bold italic.  You can't turn off a style from the base style.
29 *
30 */
31public class StyleSpan extends MetricAffectingSpan {
32
33	private int mStyle;
34
35	/**
36	 *
37	 * @param style An integer constant describing the style for this span. Examples
38	 * include bold, italic, and normal. Values are constants defined
39	 * in {@link android.graphics.Typeface}.
40	 */
41	public StyleSpan(int style) {
42		mStyle = style;
43	}
44
45	/**
46	 * Returns the style constant defined in {@link android.graphics.Typeface}.
47	 */
48	public int getStyle() {
49		return mStyle;
50	}
51
52	@Override
53    public void updateDrawState(TextPaint ds) {
54        apply(ds, mStyle);
55    }
56
57	@Override
58    public void updateMeasureState(TextPaint paint) {
59        apply(paint, mStyle);
60    }
61
62    private static void apply(Paint paint, int style) {
63        int oldStyle;
64
65        Typeface old = paint.getTypeface();
66        if (old == null) {
67            oldStyle = 0;
68        } else {
69            oldStyle = old.getStyle();
70        }
71
72        int want = oldStyle | style;
73
74        Typeface tf;
75        if (old == null) {
76            tf = Typeface.defaultFromStyle(want);
77        } else {
78            tf = Typeface.create(old, want);
79        }
80
81        int fake = want & ~tf.getStyle();
82
83        if ((fake & Typeface.BOLD) != 0) {
84            paint.setFakeBoldText(true);
85        }
86
87        if ((fake & Typeface.ITALIC) != 0) {
88            paint.setTextSkewX(-0.25f);
89        }
90
91        paint.setTypeface(tf);
92    }
93}
94