[go: nahoru, domu]

ShapeDrawable.java revision f0e06784609bd3a62cbf86499b4348f4521b6de6
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        // only draw shape if it may affect output
221        if (paint.getAlpha() != 0 || paint.getXfermode() != null || paint.hasShadow) {
222            if (mShapeState.mShape != null) {
223                // need the save both for the translate, and for the (unknown) Shape
224                int count = canvas.save();
225                canvas.translate(r.left, r.top);
226                onDraw(mShapeState.mShape, canvas, paint);
227                canvas.restoreToCount(count);
228            } else {
229                canvas.drawRect(r, paint);
230            }
231        }
232
233        // restore
234        paint.setAlpha(prevAlpha);
235    }
236
237    @Override
238    public int getChangingConfigurations() {
239        return super.getChangingConfigurations()
240                | mShapeState.mChangingConfigurations;
241    }
242
243    /**
244     * Set the alpha level for this drawable [0..255]. Note that this drawable
245     * also has a color in its paint, which has an alpha as well. These two
246     * values are automatically combined during drawing. Thus if the color's
247     * alpha is 75% (i.e. 192) and the drawable's alpha is 50% (i.e. 128), then
248     * the combined alpha that will be used during drawing will be 37.5%
249     * (i.e. 96).
250     */
251    @Override public void setAlpha(int alpha) {
252        mShapeState.mAlpha = alpha;
253        invalidateSelf();
254    }
255
256    @Override
257    public void setColorFilter(ColorFilter cf) {
258        mShapeState.mPaint.setColorFilter(cf);
259        invalidateSelf();
260    }
261
262    @Override
263    public int getOpacity() {
264        if (mShapeState.mShape == null) {
265            final Paint p = mShapeState.mPaint;
266            if (p.getXfermode() == null) {
267                final int alpha = p.getAlpha();
268                if (alpha == 0) {
269                    return PixelFormat.TRANSPARENT;
270                }
271                if (alpha == 255) {
272                    return PixelFormat.OPAQUE;
273                }
274            }
275        }
276        // not sure, so be safe
277        return PixelFormat.TRANSLUCENT;
278    }
279
280    @Override
281    public void setDither(boolean dither) {
282        mShapeState.mPaint.setDither(dither);
283        invalidateSelf();
284    }
285
286    @Override
287    protected void onBoundsChange(Rect bounds) {
288        super.onBoundsChange(bounds);
289        updateShape();
290    }
291
292    /**
293     * Subclasses override this to parse custom subelements.
294     * If you handle it, return true, else return <em>super.inflateTag(...)</em>.
295     */
296    protected boolean inflateTag(String name, Resources r, XmlPullParser parser,
297            AttributeSet attrs) {
298
299        if ("padding".equals(name)) {
300            TypedArray a = r.obtainAttributes(attrs,
301                    com.android.internal.R.styleable.ShapeDrawablePadding);
302            setPadding(
303                    a.getDimensionPixelOffset(
304                            com.android.internal.R.styleable.ShapeDrawablePadding_left, 0),
305                    a.getDimensionPixelOffset(
306                            com.android.internal.R.styleable.ShapeDrawablePadding_top, 0),
307                    a.getDimensionPixelOffset(
308                            com.android.internal.R.styleable.ShapeDrawablePadding_right, 0),
309                    a.getDimensionPixelOffset(
310                            com.android.internal.R.styleable.ShapeDrawablePadding_bottom, 0));
311            a.recycle();
312            return true;
313        }
314
315        return false;
316    }
317
318    @Override
319    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
320                        throws XmlPullParserException, IOException {
321        super.inflate(r, parser, attrs);
322
323        TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.ShapeDrawable);
324
325        int color = mShapeState.mPaint.getColor();
326        color = a.getColor(com.android.internal.R.styleable.ShapeDrawable_color, color);
327        mShapeState.mPaint.setColor(color);
328
329        boolean dither = a.getBoolean(com.android.internal.R.styleable.ShapeDrawable_dither, false);
330        mShapeState.mPaint.setDither(dither);
331
332        setIntrinsicWidth((int)
333                a.getDimension(com.android.internal.R.styleable.ShapeDrawable_width, 0f));
334        setIntrinsicHeight((int)
335                a.getDimension(com.android.internal.R.styleable.ShapeDrawable_height, 0f));
336
337        a.recycle();
338
339        int type;
340        final int outerDepth = parser.getDepth();
341        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
342               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
343            if (type != XmlPullParser.START_TAG) {
344                continue;
345            }
346
347            final String name = parser.getName();
348            // call our subclass
349            if (!inflateTag(name, r, parser, attrs)) {
350                android.util.Log.w("drawable", "Unknown element: " + name +
351                        " for ShapeDrawable " + this);
352            }
353        }
354    }
355
356    private void updateShape() {
357        if (mShapeState.mShape != null) {
358            final Rect r = getBounds();
359            final int w = r.width();
360            final int h = r.height();
361
362            mShapeState.mShape.resize(w, h);
363            if (mShapeState.mShaderFactory != null) {
364                mShapeState.mPaint.setShader(mShapeState.mShaderFactory.resize(w, h));
365            }
366        }
367        invalidateSelf();
368    }
369
370    @Override
371    public ConstantState getConstantState() {
372        mShapeState.mChangingConfigurations = getChangingConfigurations();
373        return mShapeState;
374    }
375
376    @Override
377    public Drawable mutate() {
378        if (!mMutated && super.mutate() == this) {
379            if (mShapeState.mPaint != null) {
380                mShapeState.mPaint = new Paint(mShapeState.mPaint);
381            } else {
382                mShapeState.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
383            }
384            if (mShapeState.mPadding != null) {
385                mShapeState.mPadding = new Rect(mShapeState.mPadding);
386            } else {
387                mShapeState.mPadding = new Rect();
388            }
389            try {
390                mShapeState.mShape = mShapeState.mShape.clone();
391            } catch (CloneNotSupportedException e) {
392                return null;
393            }
394            mMutated = true;
395        }
396        return this;
397    }
398
399    /**
400     * Defines the intrinsic properties of this ShapeDrawable's Shape.
401     */
402    final static class ShapeState extends ConstantState {
403        int mChangingConfigurations;
404        Paint mPaint;
405        Shape mShape;
406        Rect mPadding;
407        int mIntrinsicWidth;
408        int mIntrinsicHeight;
409        int mAlpha = 255;
410        ShaderFactory mShaderFactory;
411
412        ShapeState(ShapeState orig) {
413            if (orig != null) {
414                mPaint = orig.mPaint;
415                mShape = orig.mShape;
416                mPadding = orig.mPadding;
417                mIntrinsicWidth = orig.mIntrinsicWidth;
418                mIntrinsicHeight = orig.mIntrinsicHeight;
419                mAlpha = orig.mAlpha;
420                mShaderFactory = orig.mShaderFactory;
421            } else {
422                mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
423            }
424        }
425
426        @Override
427        public Drawable newDrawable() {
428            return new ShapeDrawable(this);
429        }
430
431        @Override
432        public Drawable newDrawable(Resources res) {
433            return new ShapeDrawable(this);
434        }
435
436        @Override
437        public int getChangingConfigurations() {
438            return mChangingConfigurations;
439        }
440    }
441
442    /**
443     * Base class defines a factory object that is called each time the drawable
444     * is resized (has a new width or height). Its resize() method returns a
445     * corresponding shader, or null.
446     * Implement this class if you'd like your ShapeDrawable to use a special
447     * {@link android.graphics.Shader}, such as a
448     * {@link android.graphics.LinearGradient}.
449     *
450     */
451    public static abstract class ShaderFactory {
452        /**
453         * Returns the Shader to be drawn when a Drawable is drawn.
454         * The dimensions of the Drawable are passed because they may be needed
455         * to adjust how the Shader is configured for drawing.
456         * This is called by ShapeDrawable.setShape().
457         *
458         * @param width  the width of the Drawable being drawn
459         * @param height the heigh of the Drawable being drawn
460         * @return       the Shader to be drawn
461         */
462        public abstract Shader resize(int width, int height);
463    }
464
465    // other subclass could wack the Shader's localmatrix based on the
466    // resize params (e.g. scaletofit, etc.). This could be used to scale
467    // a bitmap to fill the bounds without needing any other special casing.
468}
469
470