DrawableMarginSpan.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.drawable.Drawable;
20import android.graphics.Paint;
21import android.graphics.Canvas;
22import android.graphics.RectF;
23import android.text.Spanned;
24import android.text.Layout;
25
26public class DrawableMarginSpan
27implements LeadingMarginSpan, LineHeightSpan
28{
29    public DrawableMarginSpan(Drawable b) {
30        mDrawable = b;
31    }
32
33    public DrawableMarginSpan(Drawable b, int pad) {
34        mDrawable = b;
35        mPad = pad;
36    }
37
38    public int getLeadingMargin(boolean first) {
39        return mDrawable.getIntrinsicWidth() + mPad;
40    }
41
42    public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
43                                  int top, int baseline, int bottom,
44                                  CharSequence text, int start, int end,
45                                  boolean first, Layout layout) {
46        int st = ((Spanned) text).getSpanStart(this);
47        int ix = (int)x;
48        int itop = (int)layout.getLineTop(layout.getLineForOffset(st));
49
50        int dw = mDrawable.getIntrinsicWidth();
51        int dh = mDrawable.getIntrinsicHeight();
52
53        if (dir < 0)
54            x -= dw;
55
56        // XXX What to do about Paint?
57        mDrawable.setBounds(ix, itop, ix+dw, itop+dh);
58        mDrawable.draw(c);
59    }
60
61    public void chooseHeight(CharSequence text, int start, int end,
62                             int istartv, int v,
63                             Paint.FontMetricsInt fm) {
64        if (end == ((Spanned) text).getSpanEnd(this)) {
65            int ht = mDrawable.getIntrinsicHeight();
66
67            int need = ht - (v + fm.descent - fm.ascent - istartv);
68            if (need > 0)
69                fm.descent += need;
70
71            need = ht - (v + fm.bottom - fm.top - istartv);
72            if (need > 0)
73                fm.bottom += need;
74        }
75    }
76
77    private Drawable mDrawable;
78    private int mPad;
79}
80