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.graphics.*;
20import android.graphics.drawable.shapes.Shape;
21import android.content.res.Resources;
22import android.content.res.TypedArray;
23import android.util.AttributeSet;
24
25import org.xmlpull.v1.XmlPullParser;
26import org.xmlpull.v1.XmlPullParserException;
27
28import java.io.IOException;
29
30/**
31 * A Drawable object that draws primitive shapes.
32 * A ShapeDrawable takes a {@link android.graphics.drawable.shapes.Shape}
33 * object and manages its presence on the screen. If no Shape is given, then
34 * the ShapeDrawable will default to a
35 * {@link android.graphics.drawable.shapes.RectShape}.
36 *
37 * <p>This object can be defined in an XML file with the <code>&lt;shape></code> element.</p>
38 *
39 * <div class="special reference">
40 * <h3>Developer Guides</h3>
41 * <p>For more information about how to use ShapeDrawable, read the
42 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#shape-drawable">
43 * Canvas and Drawables</a> document. For more information about defining a ShapeDrawable in
44 * XML, read the
45 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html#Shape">Drawable Resources</a>
46 * document.</p></div>
47 *
48 * @attr ref android.R.styleable#ShapeDrawablePadding_left
49 * @attr ref android.R.styleable#ShapeDrawablePadding_top
50 * @attr ref android.R.styleable#ShapeDrawablePadding_right
51 * @attr ref android.R.styleable#ShapeDrawablePadding_bottom
52 * @attr ref android.R.styleable#ShapeDrawable_color
53 * @attr ref android.R.styleable#ShapeDrawable_width
54 * @attr ref android.R.styleable#ShapeDrawable_height
55 */
56public class ShapeDrawable extends Drawable {
57    private ShapeState mShapeState;
58    private boolean mMutated;
59
60    /**
61     * ShapeDrawable constructor.
62     */
63    public ShapeDrawable() {
64        this((ShapeState) null);
65    }
66
67    /**
68     * Creates a ShapeDrawable with a specified Shape.
69     *
70     * @param s the Shape that this ShapeDrawable should be
71     */
72    public ShapeDrawable(Shape s) {
73        this((ShapeState) null);
74
75        mShapeState.mShape = s;
76    }
77
78    private ShapeDrawable(ShapeState state) {
79        mShapeState = new ShapeState(state);
80    }
81
82    /**
83     * Returns the Shape of this ShapeDrawable.
84     */
85    public Shape getShape() {
86        return mShapeState.mShape;
87    }
88
89    /**
90     * Sets the Shape of this ShapeDrawable.
91     */
92    public void setShape(Shape s) {
93        mShapeState.mShape = s;
94        updateShape();
95    }
96
97    /**
98     * Sets a ShaderFactory to which requests for a
99     * {@link android.graphics.Shader} object will be made.
100     *
101     * @param fact an instance of your ShaderFactory implementation
102     */
103    public void setShaderFactory(ShaderFactory fact) {
104        mShapeState.mShaderFactory = fact;
105    }
106
107    /**
108     * Returns the ShaderFactory used by this ShapeDrawable for requesting a
109     * {@link android.graphics.Shader}.
110     */
111    public ShaderFactory getShaderFactory() {
112        return mShapeState.mShaderFactory;
113    }
114
115    /**
116     * Returns the Paint used to draw the shape.
117     */
118    public Paint getPaint() {
119        return mShapeState.mPaint;
120    }
121
122    /**
123     * Sets padding for the shape.
124     *
125     * @param left    padding for the left side (in pixels)
126     * @param top     padding for the top (in pixels)
127     * @param right   padding for the right side (in pixels)
128     * @param bottom  padding for the bottom (in pixels)
129     */
130    public void setPadding(int left, int top, int right, int bottom) {
131        if ((left | top | right | bottom) == 0) {
132            mShapeState.mPadding = null;
133        } else {
134            if (mShapeState.mPadding == null) {
135                mShapeState.mPadding = new Rect();
136            }
137            mShapeState.mPadding.set(left, top, right, bottom);
138        }
139        invalidateSelf();
140    }
141
142    /**
143     * Sets padding for this shape, defined by a Rect object.
144     * Define the padding in the Rect object as: left, top, right, bottom.
145     */
146    public void setPadding(Rect padding) {
147        if (padding == null) {
148            mShapeState.mPadding = null;
149        } else {
150            if (mShapeState.mPadding == null) {
151                mShapeState.mPadding = new Rect();
152            }
153            mShapeState.mPadding.set(padding);
154        }
155        invalidateSelf();
156    }
157
158    /**
159     * Sets the intrinsic (default) width for this shape.
160     *
161     * @param width the intrinsic width (in pixels)
162     */
163    public void setIntrinsicWidth(int width) {
164        mShapeState.mIntrinsicWidth = width;
165        invalidateSelf();
166    }
167
168    /**
169     * Sets the intrinsic (default) height for this shape.
170     *
171     * @param height the intrinsic height (in pixels)
172     */
173    public void setIntrinsicHeight(int height) {
174        mShapeState.mIntrinsicHeight = height;
175        invalidateSelf();
176    }
177
178    @Override
179    public int getIntrinsicWidth() {
180        return mShapeState.mIntrinsicWidth;
181    }
182
183    @Override
184    public int getIntrinsicHeight() {
185        return mShapeState.mIntrinsicHeight;
186    }
187
188    @Override
189    public boolean getPadding(Rect padding) {
190        if (mShapeState.mPadding != null) {
191            padding.set(mShapeState.mPadding);
192            return true;
193        } else {
194            return super.getPadding(padding);
195        }
196    }
197
198    private static int modulateAlpha(int paintAlpha, int alpha) {
199        int scale = alpha + (alpha >>> 7);  // convert to 0..256
200        return paintAlpha * scale >>> 8;
201    }
202
203    /**
204     * Called from the drawable's draw() method after the canvas has been set
205     * to draw the shape at (0,0). Subclasses can override for special effects
206     * such as multiple layers, stroking, etc.
207     */
208    protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
209        shape.draw(canvas, paint);
210    }
211
212    @Override
213    public void draw(Canvas canvas) {
214        Rect r = getBounds();
215        Paint paint = mShapeState.mPaint;
216
217        int prevAlpha = paint.getAlpha();
218        paint.setAlpha(modulateAlpha(prevAlpha, mShapeState.mAlpha));
219
220        if (mShapeState.mShape != null) {
221            // need the save both for the translate, and for the (unknown) Shape
222            int count = canvas.save();
223            canvas.translate(r.left, r.top);
224            onDraw(mShapeState.mShape, canvas, paint);
225            canvas.restoreToCount(count);
226        } else {
227            canvas.drawRect(r, paint);
228        }
229
230        // restore
231        paint.setAlpha(prevAlpha);
232    }
233
234    @Override
235    public int getChangingConfigurations() {
236        return super.getChangingConfigurations()
237                | mShapeState.mChangingConfigurations;
238    }
239
240    /**
241     * Set the alpha level for this drawable [0..255]. Note that this drawable
242     * also has a color in its paint, which has an alpha as well. These two
243     * values are automatically combined during drawing. Thus if the color's
244     * alpha is 75% (i.e. 192) and the drawable's alpha is 50% (i.e. 128), then
245     * the combined alpha that will be used during drawing will be 37.5%
246     * (i.e. 96).
247     */
248    @Override public void setAlpha(int alpha) {
249        mShapeState.mAlpha = alpha;
250        invalidateSelf();
251    }
252
253    @Override
254    public void setColorFilter(ColorFilter cf) {
255        mShapeState.mPaint.setColorFilter(cf);
256        invalidateSelf();
257    }
258
259    @Override
260    public int getOpacity() {
261        if (mShapeState.mShape == null) {
262            final Paint p = mShapeState.mPaint;
263            if (p.getXfermode() == null) {
264                final int alpha = p.getAlpha();
265                if (alpha == 0) {
266                    return PixelFormat.TRANSPARENT;
267                }
268                if (alpha == 255) {
269                    return PixelFormat.OPAQUE;
270                }
271            }
272        }
273        // not sure, so be safe
274        return PixelFormat.TRANSLUCENT;
275    }
276
277    @Override
278    public void setDither(boolean dither) {
279        mShapeState.mPaint.setDither(dither);
280        invalidateSelf();
281    }
282
283    @Override
284    protected void onBoundsChange(Rect bounds) {
285        super.onBoundsChange(bounds);
286        updateShape();
287    }
288
289    /**
290     * Subclasses override this to parse custom subelements.
291     * If you handle it, return true, else return <em>super.inflateTag(...)</em>.
292     */
293    protected boolean inflateTag(String name, Resources r, XmlPullParser parser,
294            AttributeSet attrs) {
295
296        if ("padding".equals(name)) {
297            TypedArray a = r.obtainAttributes(attrs,
298                    com.android.internal.R.styleable.ShapeDrawablePadding);
299            setPadding(
300                    a.getDimensionPixelOffset(
301                            com.android.internal.R.styleable.ShapeDrawablePadding_left, 0),
302                    a.getDimensionPixelOffset(
303                            com.android.internal.R.styleable.ShapeDrawablePadding_top, 0),
304                    a.getDimensionPixelOffset(
305                            com.android.internal.R.styleable.ShapeDrawablePadding_right, 0),
306                    a.getDimensionPixelOffset(
307                            com.android.internal.R.styleable.ShapeDrawablePadding_bottom, 0));
308            a.recycle();
309            return true;
310        }
311
312        return false;
313    }
314
315    @Override
316    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
317                        throws XmlPullParserException, IOException {
318        super.inflate(r, parser, attrs);
319
320        TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.ShapeDrawable);
321
322        int color = mShapeState.mPaint.getColor();
323        color = a.getColor(com.android.internal.R.styleable.ShapeDrawable_color, color);
324        mShapeState.mPaint.setColor(color);
325
326        boolean dither = a.getBoolean(com.android.internal.R.styleable.ShapeDrawable_dither, false);
327        mShapeState.mPaint.setDither(dither);
328
329        setIntrinsicWidth((int)
330                a.getDimension(com.android.internal.R.styleable.ShapeDrawable_width, 0f));
331        setIntrinsicHeight((int)
332                a.getDimension(com.android.internal.R.styleable.ShapeDrawable_height, 0f));
333
334        a.recycle();
335
336        int type;
337        final int outerDepth = parser.getDepth();
338        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
339               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
340            if (type != XmlPullParser.START_TAG) {
341                continue;
342            }
343
344            final String name = parser.getName();
345            // call our subclass
346            if (!inflateTag(name, r, parser, attrs)) {
347                android.util.Log.w("drawable", "Unknown element: " + name +
348                        " for ShapeDrawable " + this);
349            }
350        }
351    }
352
353    private void updateShape() {
354        if (mShapeState.mShape != null) {
355            final Rect r = getBounds();
356            final int w = r.width();
357            final int h = r.height();
358
359            mShapeState.mShape.resize(w, h);
360            if (mShapeState.mShaderFactory != null) {
361                mShapeState.mPaint.setShader(mShapeState.mShaderFactory.resize(w, h));
362            }
363        }
364        invalidateSelf();
365    }
366
367    @Override
368    public ConstantState getConstantState() {
369        mShapeState.mChangingConfigurations = getChangingConfigurations();
370        return mShapeState;
371    }
372
373    @Override
374    public Drawable mutate() {
375        if (!mMutated && super.mutate() == this) {
376            if (mShapeState.mPaint != null) {
377                mShapeState.mPaint = new Paint(mShapeState.mPaint);
378            } else {
379                mShapeState.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
380            }
381            if (mShapeState.mPadding != null) {
382                mShapeState.mPadding = new Rect(mShapeState.mPadding);
383            } else {
384                mShapeState.mPadding = new Rect();
385            }
386            try {
387                mShapeState.mShape = mShapeState.mShape.clone();
388            } catch (CloneNotSupportedException e) {
389                return null;
390            }
391            mMutated = true;
392        }
393        return this;
394    }
395
396    /**
397     * Defines the intrinsic properties of this ShapeDrawable's Shape.
398     */
399    final static class ShapeState extends ConstantState {
400        int mChangingConfigurations;
401        Paint mPaint;
402        Shape mShape;
403        Rect mPadding;
404        int mIntrinsicWidth;
405        int mIntrinsicHeight;
406        int mAlpha = 255;
407        ShaderFactory mShaderFactory;
408
409        ShapeState(ShapeState orig) {
410            if (orig != null) {
411                mPaint = orig.mPaint;
412                mShape = orig.mShape;
413                mPadding = orig.mPadding;
414                mIntrinsicWidth = orig.mIntrinsicWidth;
415                mIntrinsicHeight = orig.mIntrinsicHeight;
416                mAlpha = orig.mAlpha;
417                mShaderFactory = orig.mShaderFactory;
418            } else {
419                mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
420            }
421        }
422
423        @Override
424        public Drawable newDrawable() {
425            return new ShapeDrawable(this);
426        }
427
428        @Override
429        public Drawable newDrawable(Resources res) {
430            return new ShapeDrawable(this);
431        }
432
433        @Override
434        public int getChangingConfigurations() {
435            return mChangingConfigurations;
436        }
437    }
438
439    /**
440     * Base class defines a factory object that is called each time the drawable
441     * is resized (has a new width or height). Its resize() method returns a
442     * corresponding shader, or null.
443     * Implement this class if you'd like your ShapeDrawable to use a special
444     * {@link android.graphics.Shader}, such as a
445     * {@link android.graphics.LinearGradient}.
446     *
447     */
448    public static abstract class ShaderFactory {
449        /**
450         * Returns the Shader to be drawn when a Drawable is drawn.
451         * The dimensions of the Drawable are passed because they may be needed
452         * to adjust how the Shader is configured for drawing.
453         * This is called by ShapeDrawable.setShape().
454         *
455         * @param width  the width of the Drawable being drawn
456         * @param height the heigh of the Drawable being drawn
457         * @return       the Shader to be drawn
458         */
459        public abstract Shader resize(int width, int height);
460    }
461
462    // other subclass could wack the Shader's localmatrix based on the
463    // resize params (e.g. scaletofit, etc.). This could be used to scale
464    // a bitmap to fill the bounds without needing any other special casing.
465}
466
467