ShapeDrawable.java revision 22594f097242d9de0a538a9b8142f77da9df7ebd
1/*
2 * Copyright (C) 2007 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.graphics.drawable;
18
19import android.content.res.ColorStateList;
20import android.content.res.Resources;
21import android.content.res.TypedArray;
22import android.graphics.Canvas;
23import android.graphics.ColorFilter;
24import android.graphics.Outline;
25import android.graphics.Paint;
26import android.graphics.PixelFormat;
27import android.graphics.PorterDuff;
28import android.graphics.PorterDuff.Mode;
29import android.graphics.PorterDuffColorFilter;
30import android.graphics.Rect;
31import android.graphics.Shader;
32import android.graphics.drawable.shapes.Shape;
33import android.content.res.Resources.Theme;
34import android.util.AttributeSet;
35
36import com.android.internal.R;
37import org.xmlpull.v1.XmlPullParser;
38import org.xmlpull.v1.XmlPullParserException;
39
40import java.io.IOException;
41
42/**
43 * A Drawable object that draws primitive shapes. A ShapeDrawable takes a
44 * {@link android.graphics.drawable.shapes.Shape} object and manages its
45 * presence on the screen. If no Shape is given, then the ShapeDrawable will
46 * default to a {@link android.graphics.drawable.shapes.RectShape}.
47 * <p>
48 * This object can be defined in an XML file with the <code>&lt;shape></code>
49 * element.
50 * </p>
51 * <div class="special reference"> <h3>Developer Guides</h3>
52 * <p>
53 * For more information about how to use ShapeDrawable, read the <a
54 * href="{@docRoot}guide/topics/graphics/2d-graphics.html#shape-drawable">
55 * Canvas and Drawables</a> document. For more information about defining a
56 * ShapeDrawable in XML, read the <a href="{@docRoot}
57 * guide/topics/resources/drawable-resource.html#Shape">Drawable Resources</a>
58 * document.
59 * </p>
60 * </div>
61 *
62 * @attr ref android.R.styleable#ShapeDrawablePadding_left
63 * @attr ref android.R.styleable#ShapeDrawablePadding_top
64 * @attr ref android.R.styleable#ShapeDrawablePadding_right
65 * @attr ref android.R.styleable#ShapeDrawablePadding_bottom
66 * @attr ref android.R.styleable#ShapeDrawable_color
67 * @attr ref android.R.styleable#ShapeDrawable_width
68 * @attr ref android.R.styleable#ShapeDrawable_height
69 */
70public class ShapeDrawable extends Drawable {
71    private ShapeState mShapeState;
72    private PorterDuffColorFilter mTintFilter;
73    private boolean mMutated;
74
75    /**
76     * ShapeDrawable constructor.
77     */
78    public ShapeDrawable() {
79        this(new ShapeState(null), null, null);
80    }
81
82    /**
83     * Creates a ShapeDrawable with a specified Shape.
84     *
85     * @param s the Shape that this ShapeDrawable should be
86     */
87    public ShapeDrawable(Shape s) {
88        this(new ShapeState(null), null, null);
89
90        mShapeState.mShape = s;
91    }
92
93    /**
94     * Returns the Shape of this ShapeDrawable.
95     */
96    public Shape getShape() {
97        return mShapeState.mShape;
98    }
99
100    /**
101     * Sets the Shape of this ShapeDrawable.
102     */
103    public void setShape(Shape s) {
104        mShapeState.mShape = s;
105        updateShape();
106    }
107
108    /**
109     * Sets a ShaderFactory to which requests for a
110     * {@link android.graphics.Shader} object will be made.
111     *
112     * @param fact an instance of your ShaderFactory implementation
113     */
114    public void setShaderFactory(ShaderFactory fact) {
115        mShapeState.mShaderFactory = fact;
116    }
117
118    /**
119     * Returns the ShaderFactory used by this ShapeDrawable for requesting a
120     * {@link android.graphics.Shader}.
121     */
122    public ShaderFactory getShaderFactory() {
123        return mShapeState.mShaderFactory;
124    }
125
126    /**
127     * Returns the Paint used to draw the shape.
128     */
129    public Paint getPaint() {
130        return mShapeState.mPaint;
131    }
132
133    /**
134     * Sets padding for the shape.
135     *
136     * @param left padding for the left side (in pixels)
137     * @param top padding for the top (in pixels)
138     * @param right padding for the right side (in pixels)
139     * @param bottom padding for the bottom (in pixels)
140     */
141    public void setPadding(int left, int top, int right, int bottom) {
142        if ((left | top | right | bottom) == 0) {
143            mShapeState.mPadding = null;
144        } else {
145            if (mShapeState.mPadding == null) {
146                mShapeState.mPadding = new Rect();
147            }
148            mShapeState.mPadding.set(left, top, right, bottom);
149        }
150        invalidateSelf();
151    }
152
153    /**
154     * Sets padding for this shape, defined by a Rect object. Define the padding
155     * in the Rect object as: left, top, right, bottom.
156     */
157    public void setPadding(Rect padding) {
158        if (padding == null) {
159            mShapeState.mPadding = null;
160        } else {
161            if (mShapeState.mPadding == null) {
162                mShapeState.mPadding = new Rect();
163            }
164            mShapeState.mPadding.set(padding);
165        }
166        invalidateSelf();
167    }
168
169    /**
170     * Sets the intrinsic (default) width for this shape.
171     *
172     * @param width the intrinsic width (in pixels)
173     */
174    public void setIntrinsicWidth(int width) {
175        mShapeState.mIntrinsicWidth = width;
176        invalidateSelf();
177    }
178
179    /**
180     * Sets the intrinsic (default) height for this shape.
181     *
182     * @param height the intrinsic height (in pixels)
183     */
184    public void setIntrinsicHeight(int height) {
185        mShapeState.mIntrinsicHeight = height;
186        invalidateSelf();
187    }
188
189    @Override
190    public int getIntrinsicWidth() {
191        return mShapeState.mIntrinsicWidth;
192    }
193
194    @Override
195    public int getIntrinsicHeight() {
196        return mShapeState.mIntrinsicHeight;
197    }
198
199    @Override
200    public boolean getPadding(Rect padding) {
201        if (mShapeState.mPadding != null) {
202            padding.set(mShapeState.mPadding);
203            return true;
204        } else {
205            return super.getPadding(padding);
206        }
207    }
208
209    private static int modulateAlpha(int paintAlpha, int alpha) {
210        int scale = alpha + (alpha >>> 7); // convert to 0..256
211        return paintAlpha * scale >>> 8;
212    }
213
214    /**
215     * Called from the drawable's draw() method after the canvas has been set to
216     * draw the shape at (0,0). Subclasses can override for special effects such
217     * as multiple layers, stroking, etc.
218     */
219    protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
220        shape.draw(canvas, paint);
221    }
222
223    @Override
224    public void draw(Canvas canvas) {
225        final Rect r = getBounds();
226        final ShapeState state = mShapeState;
227        final Paint paint = state.mPaint;
228
229        final int prevAlpha = paint.getAlpha();
230        paint.setAlpha(modulateAlpha(prevAlpha, state.mAlpha));
231
232        // only draw shape if it may affect output
233        if (paint.getAlpha() != 0 || paint.getXfermode() != null || paint.hasShadowLayer()) {
234            final boolean clearColorFilter;
235            if (mTintFilter != null && paint.getColorFilter() == null) {
236                paint.setColorFilter(mTintFilter);
237                clearColorFilter = true;
238            } else {
239                clearColorFilter = false;
240            }
241
242            if (state.mShape != null) {
243                // need the save both for the translate, and for the (unknown)
244                // Shape
245                final int count = canvas.save();
246                canvas.translate(r.left, r.top);
247                onDraw(state.mShape, canvas, paint);
248                canvas.restoreToCount(count);
249            } else {
250                canvas.drawRect(r, paint);
251            }
252
253            if (clearColorFilter) {
254                paint.setColorFilter(null);
255            }
256        }
257
258        // restore
259        paint.setAlpha(prevAlpha);
260    }
261
262    @Override
263    public int getChangingConfigurations() {
264        return super.getChangingConfigurations()
265                | mShapeState.mChangingConfigurations;
266    }
267
268    /**
269     * Set the alpha level for this drawable [0..255]. Note that this drawable
270     * also has a color in its paint, which has an alpha as well. These two
271     * values are automatically combined during drawing. Thus if the color's
272     * alpha is 75% (i.e. 192) and the drawable's alpha is 50% (i.e. 128), then
273     * the combined alpha that will be used during drawing will be 37.5% (i.e.
274     * 96).
275     */
276    @Override
277    public void setAlpha(int alpha) {
278        mShapeState.mAlpha = alpha;
279        invalidateSelf();
280    }
281
282    @Override
283    public int getAlpha() {
284        return mShapeState.mAlpha;
285    }
286
287    @Override
288    public void setTint(ColorStateList tint, PorterDuff.Mode tintMode) {
289        final ShapeState state = mShapeState;
290        state.mTint = tint;
291        state.mTintMode = tintMode;
292
293        mTintFilter = updateTintFilter(mTintFilter, tint, tintMode);
294        invalidateSelf();
295    }
296
297    @Override
298    public void setColorFilter(ColorFilter cf) {
299        mShapeState.mPaint.setColorFilter(cf);
300        invalidateSelf();
301    }
302
303    @Override
304    public int getOpacity() {
305        if (mShapeState.mShape == null) {
306            final Paint p = mShapeState.mPaint;
307            if (p.getXfermode() == null) {
308                final int alpha = p.getAlpha();
309                if (alpha == 0) {
310                    return PixelFormat.TRANSPARENT;
311                }
312                if (alpha == 255) {
313                    return PixelFormat.OPAQUE;
314                }
315            }
316        }
317        // not sure, so be safe
318        return PixelFormat.TRANSLUCENT;
319    }
320
321    @Override
322    public void setDither(boolean dither) {
323        mShapeState.mPaint.setDither(dither);
324        invalidateSelf();
325    }
326
327    @Override
328    protected void onBoundsChange(Rect bounds) {
329        super.onBoundsChange(bounds);
330        updateShape();
331    }
332
333    @Override
334    protected boolean onStateChange(int[] stateSet) {
335        final ShapeState state = mShapeState;
336        if (state.mTint != null && state.mTintMode != null) {
337            mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
338            return true;
339        }
340        return false;
341    }
342
343    @Override
344    public boolean isStateful() {
345        final ShapeState s = mShapeState;
346        return super.isStateful() || (s.mTint != null && s.mTint.isStateful());
347    }
348
349    /**
350     * Subclasses override this to parse custom subelements. If you handle it,
351     * return true, else return <em>super.inflateTag(...)</em>.
352     */
353    protected boolean inflateTag(String name, Resources r, XmlPullParser parser,
354            AttributeSet attrs) {
355
356        if ("padding".equals(name)) {
357            TypedArray a = r.obtainAttributes(attrs,
358                    com.android.internal.R.styleable.ShapeDrawablePadding);
359            setPadding(
360                    a.getDimensionPixelOffset(
361                            com.android.internal.R.styleable.ShapeDrawablePadding_left, 0),
362                    a.getDimensionPixelOffset(
363                            com.android.internal.R.styleable.ShapeDrawablePadding_top, 0),
364                    a.getDimensionPixelOffset(
365                            com.android.internal.R.styleable.ShapeDrawablePadding_right, 0),
366                    a.getDimensionPixelOffset(
367                            com.android.internal.R.styleable.ShapeDrawablePadding_bottom, 0));
368            a.recycle();
369            return true;
370        }
371
372        return false;
373    }
374
375    @Override
376    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme)
377            throws XmlPullParserException, IOException {
378        super.inflate(r, parser, attrs, theme);
379
380        final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.ShapeDrawable);
381        updateStateFromTypedArray(a);
382        a.recycle();
383
384        int type;
385        final int outerDepth = parser.getDepth();
386        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
387                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
388            if (type != XmlPullParser.START_TAG) {
389                continue;
390            }
391
392            final String name = parser.getName();
393            // call our subclass
394            if (!inflateTag(name, r, parser, attrs)) {
395                android.util.Log.w("drawable", "Unknown element: " + name +
396                        " for ShapeDrawable " + this);
397            }
398        }
399
400        // Update local properties.
401        initializeWithState(mShapeState, r);
402    }
403
404    @Override
405    public void applyTheme(Theme t) {
406        super.applyTheme(t);
407
408        final ShapeState state = mShapeState;
409        if (state == null || state.mThemeAttrs == null) {
410            return;
411        }
412
413        final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.ShapeDrawable);
414        updateStateFromTypedArray(a);
415        a.recycle();
416
417        // Update local properties.
418        initializeWithState(state, t.getResources());
419    }
420
421    private void updateStateFromTypedArray(TypedArray a) {
422        final ShapeState state = mShapeState;
423        final Paint paint = state.mPaint;
424
425        // Extract the theme attributes, if any.
426        state.mThemeAttrs = a.extractThemeAttrs();
427
428        int color = paint.getColor();
429        color = a.getColor(R.styleable.ShapeDrawable_color, color);
430        paint.setColor(color);
431
432        boolean dither = paint.isDither();
433        dither = a.getBoolean(R.styleable.ShapeDrawable_dither, dither);
434        paint.setDither(dither);
435
436        setIntrinsicWidth((int) a.getDimension(
437                R.styleable.ShapeDrawable_width, state.mIntrinsicWidth));
438        setIntrinsicHeight((int) a.getDimension(
439                R.styleable.ShapeDrawable_height, state.mIntrinsicHeight));
440
441        final int tintMode = a.getInt(R.styleable.ShapeDrawable_tintMode, -1);
442        if (tintMode != -1) {
443            state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN);
444        }
445
446        final ColorStateList tint = a.getColorStateList(R.styleable.ShapeDrawable_tint);
447        if (tint != null) {
448            state.mTint = tint;
449        }
450    }
451
452    private void updateShape() {
453        if (mShapeState.mShape != null) {
454            final Rect r = getBounds();
455            final int w = r.width();
456            final int h = r.height();
457
458            mShapeState.mShape.resize(w, h);
459            if (mShapeState.mShaderFactory != null) {
460                mShapeState.mPaint.setShader(mShapeState.mShaderFactory.resize(w, h));
461            }
462        }
463        invalidateSelf();
464    }
465
466    @Override
467    public boolean getOutline(Outline outline) {
468        if (mShapeState.mShape == null) {
469            // don't publish outline without a shape
470            return false;
471        }
472
473        return mShapeState.mShape.getOutline(outline);
474    }
475
476    @Override
477    public ConstantState getConstantState() {
478        mShapeState.mChangingConfigurations = getChangingConfigurations();
479        return mShapeState;
480    }
481
482    @Override
483    public Drawable mutate() {
484        if (!mMutated && super.mutate() == this) {
485            if (mShapeState.mPaint != null) {
486                mShapeState.mPaint = new Paint(mShapeState.mPaint);
487            } else {
488                mShapeState.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
489            }
490            if (mShapeState.mPadding != null) {
491                mShapeState.mPadding = new Rect(mShapeState.mPadding);
492            } else {
493                mShapeState.mPadding = new Rect();
494            }
495            try {
496                mShapeState.mShape = mShapeState.mShape.clone();
497            } catch (CloneNotSupportedException e) {
498                return null;
499            }
500            mMutated = true;
501        }
502        return this;
503    }
504
505    /**
506     * Defines the intrinsic properties of this ShapeDrawable's Shape.
507     */
508    final static class ShapeState extends ConstantState {
509        int[] mThemeAttrs;
510        int mChangingConfigurations;
511        Paint mPaint;
512        Shape mShape;
513        ColorStateList mTint;
514        Mode mTintMode = Mode.SRC_IN;
515        Rect mPadding;
516        int mIntrinsicWidth;
517        int mIntrinsicHeight;
518        int mAlpha = 255;
519        ShaderFactory mShaderFactory;
520
521        ShapeState(ShapeState orig) {
522            if (orig != null) {
523                mThemeAttrs = orig.mThemeAttrs;
524                mPaint = orig.mPaint;
525                mShape = orig.mShape;
526                mTint = orig.mTint;
527                mTintMode = orig.mTintMode;
528                mPadding = orig.mPadding;
529                mIntrinsicWidth = orig.mIntrinsicWidth;
530                mIntrinsicHeight = orig.mIntrinsicHeight;
531                mAlpha = orig.mAlpha;
532                mShaderFactory = orig.mShaderFactory;
533            } else {
534                mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
535            }
536        }
537
538        @Override
539        public boolean canApplyTheme() {
540            return mThemeAttrs != null;
541        }
542
543        @Override
544        public Drawable newDrawable() {
545            return new ShapeDrawable(this, null, null);
546        }
547
548        @Override
549        public Drawable newDrawable(Resources res) {
550            return new ShapeDrawable(this, res, null);
551        }
552
553        @Override
554        public Drawable newDrawable(Resources res, Theme theme) {
555            return new ShapeDrawable(this, res, theme);
556        }
557
558        @Override
559        public int getChangingConfigurations() {
560            return mChangingConfigurations;
561        }
562    }
563
564    /**
565     * The one constructor to rule them all. This is called by all public
566     * constructors to set the state and initialize local properties.
567     */
568    private ShapeDrawable(ShapeState state, Resources res, Theme theme) {
569        if (theme != null && state.canApplyTheme()) {
570            mShapeState = new ShapeState(state);
571            applyTheme(theme);
572        } else {
573            mShapeState = state;
574        }
575
576        initializeWithState(state, res);
577    }
578
579    /**
580     * Initializes local dynamic properties from state. This should be called
581     * after significant state changes, e.g. from the One True Constructor and
582     * after inflating or applying a theme.
583     */
584    private void initializeWithState(ShapeState state, Resources res) {
585        mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
586    }
587
588    /**
589     * Base class defines a factory object that is called each time the drawable
590     * is resized (has a new width or height). Its resize() method returns a
591     * corresponding shader, or null. Implement this class if you'd like your
592     * ShapeDrawable to use a special {@link android.graphics.Shader}, such as a
593     * {@link android.graphics.LinearGradient}.
594     */
595    public static abstract class ShaderFactory {
596        /**
597         * Returns the Shader to be drawn when a Drawable is drawn. The
598         * dimensions of the Drawable are passed because they may be needed to
599         * adjust how the Shader is configured for drawing. This is called by
600         * ShapeDrawable.setShape().
601         *
602         * @param width the width of the Drawable being drawn
603         * @param height the heigh of the Drawable being drawn
604         * @return the Shader to be drawn
605         */
606        public abstract Shader resize(int width, int height);
607    }
608
609    // other subclass could wack the Shader's localmatrix based on the
610    // resize params (e.g. scaletofit, etc.). This could be used to scale
611    // a bitmap to fill the bounds without needing any other special casing.
612}
613