ShapeDrawable.java revision 77b5cad3efedd20f2b7cc14d87ccce1b0261960a
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        // Account for any configuration changes.
426        state.mChangingConfigurations |= a.getChangingConfigurations();
427
428        // Extract the theme attributes, if any.
429        state.mThemeAttrs = a.extractThemeAttrs();
430
431        int color = paint.getColor();
432        color = a.getColor(R.styleable.ShapeDrawable_color, color);
433        paint.setColor(color);
434
435        boolean dither = paint.isDither();
436        dither = a.getBoolean(R.styleable.ShapeDrawable_dither, dither);
437        paint.setDither(dither);
438
439        setIntrinsicWidth((int) a.getDimension(
440                R.styleable.ShapeDrawable_width, state.mIntrinsicWidth));
441        setIntrinsicHeight((int) a.getDimension(
442                R.styleable.ShapeDrawable_height, state.mIntrinsicHeight));
443
444        final int tintMode = a.getInt(R.styleable.ShapeDrawable_tintMode, -1);
445        if (tintMode != -1) {
446            state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN);
447        }
448
449        final ColorStateList tint = a.getColorStateList(R.styleable.ShapeDrawable_tint);
450        if (tint != null) {
451            state.mTint = tint;
452        }
453    }
454
455    private void updateShape() {
456        if (mShapeState.mShape != null) {
457            final Rect r = getBounds();
458            final int w = r.width();
459            final int h = r.height();
460
461            mShapeState.mShape.resize(w, h);
462            if (mShapeState.mShaderFactory != null) {
463                mShapeState.mPaint.setShader(mShapeState.mShaderFactory.resize(w, h));
464            }
465        }
466        invalidateSelf();
467    }
468
469    @Override
470    public void getOutline(Outline outline) {
471        if (mShapeState.mShape != null) {
472            mShapeState.mShape.getOutline(outline);
473            outline.setAlpha(getAlpha() / 255.0f);
474        }
475    }
476
477    @Override
478    public ConstantState getConstantState() {
479        mShapeState.mChangingConfigurations = getChangingConfigurations();
480        return mShapeState;
481    }
482
483    @Override
484    public Drawable mutate() {
485        if (!mMutated && super.mutate() == this) {
486            if (mShapeState.mPaint != null) {
487                mShapeState.mPaint = new Paint(mShapeState.mPaint);
488            } else {
489                mShapeState.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
490            }
491            if (mShapeState.mPadding != null) {
492                mShapeState.mPadding = new Rect(mShapeState.mPadding);
493            } else {
494                mShapeState.mPadding = new Rect();
495            }
496            try {
497                mShapeState.mShape = mShapeState.mShape.clone();
498            } catch (CloneNotSupportedException e) {
499                return null;
500            }
501            mMutated = true;
502        }
503        return this;
504    }
505
506    /**
507     * Defines the intrinsic properties of this ShapeDrawable's Shape.
508     */
509    final static class ShapeState extends ConstantState {
510        int[] mThemeAttrs;
511        int mChangingConfigurations;
512        Paint mPaint;
513        Shape mShape;
514        ColorStateList mTint;
515        Mode mTintMode = Mode.SRC_IN;
516        Rect mPadding;
517        int mIntrinsicWidth;
518        int mIntrinsicHeight;
519        int mAlpha = 255;
520        ShaderFactory mShaderFactory;
521
522        ShapeState(ShapeState orig) {
523            if (orig != null) {
524                mThemeAttrs = orig.mThemeAttrs;
525                mPaint = orig.mPaint;
526                mShape = orig.mShape;
527                mTint = orig.mTint;
528                mTintMode = orig.mTintMode;
529                mPadding = orig.mPadding;
530                mIntrinsicWidth = orig.mIntrinsicWidth;
531                mIntrinsicHeight = orig.mIntrinsicHeight;
532                mAlpha = orig.mAlpha;
533                mShaderFactory = orig.mShaderFactory;
534            } else {
535                mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
536            }
537        }
538
539        @Override
540        public boolean canApplyTheme() {
541            return mThemeAttrs != null;
542        }
543
544        @Override
545        public Drawable newDrawable() {
546            return new ShapeDrawable(this, null, null);
547        }
548
549        @Override
550        public Drawable newDrawable(Resources res) {
551            return new ShapeDrawable(this, res, null);
552        }
553
554        @Override
555        public Drawable newDrawable(Resources res, Theme theme) {
556            return new ShapeDrawable(this, res, theme);
557        }
558
559        @Override
560        public int getChangingConfigurations() {
561            return mChangingConfigurations;
562        }
563    }
564
565    /**
566     * The one constructor to rule them all. This is called by all public
567     * constructors to set the state and initialize local properties.
568     */
569    private ShapeDrawable(ShapeState state, Resources res, Theme theme) {
570        if (theme != null && state.canApplyTheme()) {
571            mShapeState = new ShapeState(state);
572            applyTheme(theme);
573        } else {
574            mShapeState = state;
575        }
576
577        initializeWithState(state, res);
578    }
579
580    /**
581     * Initializes local dynamic properties from state. This should be called
582     * after significant state changes, e.g. from the One True Constructor and
583     * after inflating or applying a theme.
584     */
585    private void initializeWithState(ShapeState state, Resources res) {
586        mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
587    }
588
589    /**
590     * Base class defines a factory object that is called each time the drawable
591     * is resized (has a new width or height). Its resize() method returns a
592     * corresponding shader, or null. Implement this class if you'd like your
593     * ShapeDrawable to use a special {@link android.graphics.Shader}, such as a
594     * {@link android.graphics.LinearGradient}.
595     */
596    public static abstract class ShaderFactory {
597        /**
598         * Returns the Shader to be drawn when a Drawable is drawn. The
599         * dimensions of the Drawable are passed because they may be needed to
600         * adjust how the Shader is configured for drawing. This is called by
601         * ShapeDrawable.setShape().
602         *
603         * @param width the width of the Drawable being drawn
604         * @param height the heigh of the Drawable being drawn
605         * @return the Shader to be drawn
606         */
607        public abstract Shader resize(int width, int height);
608    }
609
610    // other subclass could wack the Shader's localmatrix based on the
611    // resize params (e.g. scaletofit, etc.). This could be used to scale
612    // a bitmap to fill the bounds without needing any other special casing.
613}
614