DynamicDrawableSpan.java revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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.Canvas;
20import android.graphics.Paint;
21import android.graphics.Rect;
22import android.graphics.drawable.Drawable;
23
24import java.lang.ref.WeakReference;
25
26/**
27 *
28 */
29public abstract class DynamicDrawableSpan
30extends ReplacementSpan
31{
32    /**
33     * Your subclass must implement this method to provide the bitmap
34     * to be drawn.  The dimensions of the bitmap must be the same
35     * from each call to the next.
36     */
37    public abstract Drawable getDrawable();
38
39    @Override
40    public int getSize(Paint paint, CharSequence text,
41                         int start, int end,
42                         Paint.FontMetricsInt fm) {
43        Drawable d = getCachedDrawable();
44        Rect rect = d.getBounds();
45
46        if (fm != null) {
47            fm.ascent = -rect.bottom;
48            fm.descent = 0;
49
50            fm.top = fm.ascent;
51            fm.bottom = 0;
52        }
53
54        return rect.right;
55    }
56
57    @Override
58    public void draw(Canvas canvas, CharSequence text,
59                     int start, int end, float x,
60                     int top, int y, int bottom, Paint paint) {
61        Drawable b = getCachedDrawable();
62        canvas.save();
63
64        canvas.translate(x, bottom - b.getBounds().bottom);
65        b.draw(canvas);
66        canvas.restore();
67    }
68
69    private Drawable getCachedDrawable() {
70        WeakReference<Drawable> wr = mDrawableRef;
71        Drawable d = null;
72
73        if (wr != null)
74            d = wr.get();
75
76        if (d == null) {
77            d = getDrawable();
78            mDrawableRef = new WeakReference<Drawable>(d);
79        }
80
81        return d;
82    }
83
84    private WeakReference<Drawable> mDrawableRef;
85}
86
87