Drawable.java revision d9e788c4f0528e46db4a035cfac043736becb0d1
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.graphics.drawable; 18 19import android.graphics.Insets; 20import android.graphics.Xfermode; 21import android.os.Trace; 22import org.xmlpull.v1.XmlPullParser; 23import org.xmlpull.v1.XmlPullParserException; 24 25import android.content.res.Resources; 26import android.content.res.TypedArray; 27import android.graphics.Bitmap; 28import android.graphics.BitmapFactory; 29import android.graphics.Canvas; 30import android.graphics.ColorFilter; 31import android.graphics.NinePatch; 32import android.graphics.PixelFormat; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffColorFilter; 35import android.graphics.Rect; 36import android.graphics.Region; 37import android.util.AttributeSet; 38import android.util.DisplayMetrics; 39import android.util.StateSet; 40import android.util.TypedValue; 41import android.util.Xml; 42import android.view.View; 43 44import java.io.IOException; 45import java.io.InputStream; 46import java.lang.ref.WeakReference; 47import java.util.Arrays; 48 49/** 50 * A Drawable is a general abstraction for "something that can be drawn." Most 51 * often you will deal with Drawable as the type of resource retrieved for 52 * drawing things to the screen; the Drawable class provides a generic API for 53 * dealing with an underlying visual resource that may take a variety of forms. 54 * Unlike a {@link android.view.View}, a Drawable does not have any facility to 55 * receive events or otherwise interact with the user. 56 * 57 * <p>In addition to simple drawing, Drawable provides a number of generic 58 * mechanisms for its client to interact with what is being drawn: 59 * 60 * <ul> 61 * <li> The {@link #setBounds} method <var>must</var> be called to tell the 62 * Drawable where it is drawn and how large it should be. All Drawables 63 * should respect the requested size, often simply by scaling their 64 * imagery. A client can find the preferred size for some Drawables with 65 * the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods. 66 * 67 * <li> The {@link #getPadding} method can return from some Drawables 68 * information about how to frame content that is placed inside of them. 69 * For example, a Drawable that is intended to be the frame for a button 70 * widget would need to return padding that correctly places the label 71 * inside of itself. 72 * 73 * <li> The {@link #setState} method allows the client to tell the Drawable 74 * in which state it is to be drawn, such as "focused", "selected", etc. 75 * Some drawables may modify their imagery based on the selected state. 76 * 77 * <li> The {@link #setLevel} method allows the client to supply a single 78 * continuous controller that can modify the Drawable is displayed, such as 79 * a battery level or progress level. Some drawables may modify their 80 * imagery based on the current level. 81 * 82 * <li> A Drawable can perform animations by calling back to its client 83 * through the {@link Callback} interface. All clients should support this 84 * interface (via {@link #setCallback}) so that animations will work. A 85 * simple way to do this is through the system facilities such as 86 * {@link android.view.View#setBackground(Drawable)} and 87 * {@link android.widget.ImageView}. 88 * </ul> 89 * 90 * Though usually not visible to the application, Drawables may take a variety 91 * of forms: 92 * 93 * <ul> 94 * <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image. 95 * <li> <b>Nine Patch</b>: an extension to the PNG format allows it to 96 * specify information about how to stretch it and place things inside of 97 * it. 98 * <li> <b>Shape</b>: contains simple drawing commands instead of a raw 99 * bitmap, allowing it to resize better in some cases. 100 * <li> <b>Layers</b>: a compound drawable, which draws multiple underlying 101 * drawables on top of each other. 102 * <li> <b>States</b>: a compound drawable that selects one of a set of 103 * drawables based on its state. 104 * <li> <b>Levels</b>: a compound drawable that selects one of a set of 105 * drawables based on its level. 106 * <li> <b>Scale</b>: a compound drawable with a single child drawable, 107 * whose overall size is modified based on the current level. 108 * </ul> 109 * 110 * <div class="special reference"> 111 * <h3>Developer Guides</h3> 112 * <p>For more information about how to use drawables, read the 113 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer 114 * guide. For information and examples of creating drawable resources (XML or bitmap files that 115 * can be loaded in code), read the 116 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a> 117 * document.</p></div> 118 */ 119public abstract class Drawable { 120 /** 121 * Hotspot identifier mask for tracking touch points. 122 * 123 * @hide until hotspot APIs are finalized 124 */ 125 public static final int HOTSPOT_TOUCH_MASK = 0xFF; 126 127 /** 128 * Hotspot identifier for tracking keyboard focus. 129 * 130 * @hide until hotspot APIs are finalized 131 */ 132 public static final int HOTSPOT_FOCUS = 0x100; 133 134 private static final Rect ZERO_BOUNDS_RECT = new Rect(); 135 136 private int[] mStateSet = StateSet.WILD_CARD; 137 private int mLevel = 0; 138 private int mChangingConfigurations = 0; 139 private Rect mBounds = ZERO_BOUNDS_RECT; // lazily becomes a new Rect() 140 private WeakReference<Callback> mCallback = null; 141 private boolean mVisible = true; 142 143 private int mLayoutDirection; 144 145 /** 146 * Draw in its bounds (set via setBounds) respecting optional effects such 147 * as alpha (set via setAlpha) and color filter (set via setColorFilter). 148 * 149 * @param canvas The canvas to draw into 150 */ 151 public abstract void draw(Canvas canvas); 152 153 /** 154 * Specify a bounding rectangle for the Drawable. This is where the drawable 155 * will draw when its draw() method is called. 156 */ 157 public void setBounds(int left, int top, int right, int bottom) { 158 Rect oldBounds = mBounds; 159 160 if (oldBounds == ZERO_BOUNDS_RECT) { 161 oldBounds = mBounds = new Rect(); 162 } 163 164 if (oldBounds.left != left || oldBounds.top != top || 165 oldBounds.right != right || oldBounds.bottom != bottom) { 166 if (!oldBounds.isEmpty()) { 167 // first invalidate the previous bounds 168 invalidateSelf(); 169 } 170 mBounds.set(left, top, right, bottom); 171 onBoundsChange(mBounds); 172 } 173 } 174 175 /** 176 * Specify a bounding rectangle for the Drawable. This is where the drawable 177 * will draw when its draw() method is called. 178 */ 179 public void setBounds(Rect bounds) { 180 setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom); 181 } 182 183 /** 184 * Return a copy of the drawable's bounds in the specified Rect (allocated 185 * by the caller). The bounds specify where this will draw when its draw() 186 * method is called. 187 * 188 * @param bounds Rect to receive the drawable's bounds (allocated by the 189 * caller). 190 */ 191 public final void copyBounds(Rect bounds) { 192 bounds.set(mBounds); 193 } 194 195 /** 196 * Return a copy of the drawable's bounds in a new Rect. This returns the 197 * same values as getBounds(), but the returned object is guaranteed to not 198 * be changed later by the drawable (i.e. it retains no reference to this 199 * rect). If the caller already has a Rect allocated, call copyBounds(rect). 200 * 201 * @return A copy of the drawable's bounds 202 */ 203 public final Rect copyBounds() { 204 return new Rect(mBounds); 205 } 206 207 /** 208 * Return the drawable's bounds Rect. Note: for efficiency, the returned 209 * object may be the same object stored in the drawable (though this is not 210 * guaranteed), so if a persistent copy of the bounds is needed, call 211 * copyBounds(rect) instead. 212 * You should also not change the object returned by this method as it may 213 * be the same object stored in the drawable. 214 * 215 * @return The bounds of the drawable (which may change later, so caller 216 * beware). DO NOT ALTER the returned object as it may change the 217 * stored bounds of this drawable. 218 * 219 * @see #copyBounds() 220 * @see #copyBounds(android.graphics.Rect) 221 */ 222 public final Rect getBounds() { 223 if (mBounds == ZERO_BOUNDS_RECT) { 224 mBounds = new Rect(); 225 } 226 227 return mBounds; 228 } 229 230 /** 231 * Set a mask of the configuration parameters for which this drawable 232 * may change, requiring that it be re-created. 233 * 234 * @param configs A mask of the changing configuration parameters, as 235 * defined by {@link android.content.res.Configuration}. 236 * 237 * @see android.content.res.Configuration 238 */ 239 public void setChangingConfigurations(int configs) { 240 mChangingConfigurations = configs; 241 } 242 243 /** 244 * Return a mask of the configuration parameters for which this drawable 245 * may change, requiring that it be re-created. The default implementation 246 * returns whatever was provided through 247 * {@link #setChangingConfigurations(int)} or 0 by default. Subclasses 248 * may extend this to or in the changing configurations of any other 249 * drawables they hold. 250 * 251 * @return Returns a mask of the changing configuration parameters, as 252 * defined by {@link android.content.res.Configuration}. 253 * 254 * @see android.content.res.Configuration 255 */ 256 public int getChangingConfigurations() { 257 return mChangingConfigurations; 258 } 259 260 /** 261 * Set to true to have the drawable dither its colors when drawn to a device 262 * with fewer than 8-bits per color component. This can improve the look on 263 * those devices, but can also slow down the drawing a little. 264 */ 265 public void setDither(boolean dither) {} 266 267 /** 268 * Set to true to have the drawable filter its bitmap when scaled or rotated 269 * (for drawables that use bitmaps). If the drawable does not use bitmaps, 270 * this call is ignored. This can improve the look when scaled or rotated, 271 * but also slows down the drawing. 272 */ 273 public void setFilterBitmap(boolean filter) {} 274 275 /** 276 * Implement this interface if you want to create an animated drawable that 277 * extends {@link android.graphics.drawable.Drawable Drawable}. 278 * Upon retrieving a drawable, use 279 * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)} 280 * to supply your implementation of the interface to the drawable; it uses 281 * this interface to schedule and execute animation changes. 282 */ 283 public static interface Callback { 284 /** 285 * Called when the drawable needs to be redrawn. A view at this point 286 * should invalidate itself (or at least the part of itself where the 287 * drawable appears). 288 * 289 * @param who The drawable that is requesting the update. 290 */ 291 public void invalidateDrawable(Drawable who); 292 293 /** 294 * A Drawable can call this to schedule the next frame of its 295 * animation. An implementation can generally simply call 296 * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with 297 * the parameters <var>(what, who, when)</var> to perform the 298 * scheduling. 299 * 300 * @param who The drawable being scheduled. 301 * @param what The action to execute. 302 * @param when The time (in milliseconds) to run. The timebase is 303 * {@link android.os.SystemClock#uptimeMillis} 304 */ 305 public void scheduleDrawable(Drawable who, Runnable what, long when); 306 307 /** 308 * A Drawable can call this to unschedule an action previously 309 * scheduled with {@link #scheduleDrawable}. An implementation can 310 * generally simply call 311 * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with 312 * the parameters <var>(what, who)</var> to unschedule the drawable. 313 * 314 * @param who The drawable being unscheduled. 315 * @param what The action being unscheduled. 316 */ 317 public void unscheduleDrawable(Drawable who, Runnable what); 318 } 319 320 /** 321 * Bind a {@link Callback} object to this Drawable. Required for clients 322 * that want to support animated drawables. 323 * 324 * @param cb The client's Callback implementation. 325 * 326 * @see #getCallback() 327 */ 328 public final void setCallback(Callback cb) { 329 mCallback = new WeakReference<Callback>(cb); 330 } 331 332 /** 333 * Return the current {@link Callback} implementation attached to this 334 * Drawable. 335 * 336 * @return A {@link Callback} instance or null if no callback was set. 337 * 338 * @see #setCallback(android.graphics.drawable.Drawable.Callback) 339 */ 340 public Callback getCallback() { 341 if (mCallback != null) { 342 return mCallback.get(); 343 } 344 return null; 345 } 346 347 /** 348 * Use the current {@link Callback} implementation to have this Drawable 349 * redrawn. Does nothing if there is no Callback attached to the 350 * Drawable. 351 * 352 * @see Callback#invalidateDrawable 353 * @see #getCallback() 354 * @see #setCallback(android.graphics.drawable.Drawable.Callback) 355 */ 356 public void invalidateSelf() { 357 final Callback callback = getCallback(); 358 if (callback != null) { 359 callback.invalidateDrawable(this); 360 } 361 } 362 363 /** 364 * Use the current {@link Callback} implementation to have this Drawable 365 * scheduled. Does nothing if there is no Callback attached to the 366 * Drawable. 367 * 368 * @param what The action being scheduled. 369 * @param when The time (in milliseconds) to run. 370 * 371 * @see Callback#scheduleDrawable 372 */ 373 public void scheduleSelf(Runnable what, long when) { 374 final Callback callback = getCallback(); 375 if (callback != null) { 376 callback.scheduleDrawable(this, what, when); 377 } 378 } 379 380 /** 381 * Use the current {@link Callback} implementation to have this Drawable 382 * unscheduled. Does nothing if there is no Callback attached to the 383 * Drawable. 384 * 385 * @param what The runnable that you no longer want called. 386 * 387 * @see Callback#unscheduleDrawable 388 */ 389 public void unscheduleSelf(Runnable what) { 390 final Callback callback = getCallback(); 391 if (callback != null) { 392 callback.unscheduleDrawable(this, what); 393 } 394 } 395 396 /** 397 * Returns the resolved layout direction for this Drawable. 398 * 399 * @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR}, 400 * {@link android.view.View#LAYOUT_DIRECTION_RTL} 401 * 402 * @hide 403 */ 404 public int getLayoutDirection() { 405 return mLayoutDirection; 406 } 407 408 /** 409 * Set the layout direction for this drawable. Should be a resolved direction as the 410 * Drawable as no capacity to do the resolution on his own. 411 * 412 * @param layoutDirection One of {@link android.view.View#LAYOUT_DIRECTION_LTR}, 413 * {@link android.view.View#LAYOUT_DIRECTION_RTL} 414 * 415 * @hide 416 */ 417 public void setLayoutDirection(@View.ResolvedLayoutDir int layoutDirection) { 418 if (getLayoutDirection() != layoutDirection) { 419 mLayoutDirection = layoutDirection; 420 } 421 } 422 423 /** 424 * Specify an alpha value for the drawable. 0 means fully transparent, and 425 * 255 means fully opaque. 426 */ 427 public abstract void setAlpha(int alpha); 428 429 /** 430 * Gets the current alpha value for the drawable. 0 means fully transparent, 431 * 255 means fully opaque. This method is implemented by 432 * Drawable subclasses and the value returned is specific to how that class treats alpha. 433 * The default return value is 255 if the class does not override this method to return a value 434 * specific to its use of alpha. 435 */ 436 public int getAlpha() { 437 return 0xFF; 438 } 439 440 /** 441 * Specify an optional color filter for the drawable. Pass null to remove 442 * any existing color filter. 443 */ 444 public abstract void setColorFilter(ColorFilter cf); 445 446 /** 447 * @hide Consider for future API inclusion 448 */ 449 public void setXfermode(Xfermode mode) { 450 // Base implementation drops it on the floor for compatibility. Whee! 451 // TODO: For this to be included in the API proper, all framework drawables need impls. 452 // For right now only BitmapDrawable has it. 453 } 454 455 /** 456 * Specify a color and Porter-Duff mode to be the color filter for this 457 * drawable. 458 */ 459 public void setColorFilter(int color, PorterDuff.Mode mode) { 460 setColorFilter(new PorterDuffColorFilter(color, mode)); 461 } 462 463 /** 464 * Removes the color filter for this drawable. 465 */ 466 public void clearColorFilter() { 467 setColorFilter(null); 468 } 469 470 /** 471 * Indicates whether the drawable supports hotspots. Hotspots are uniquely 472 * identifiable coordinates the may be added, updated and removed within the 473 * drawable. 474 * 475 * @return true if hotspots are supported 476 * @see #setHotspot(int, float, float) 477 * @see #removeHotspot(int) 478 * @see #clearHotspots() 479 * @hide until hotspot APIs are finalized 480 */ 481 public boolean supportsHotspots() { 482 return false; 483 } 484 485 /** 486 * Specifies a hotspot's location within the drawable. 487 * 488 * @param id unique identifier for the hotspot 489 * @param x x-coordinate 490 * @param y y-coordinate 491 * @hide until hotspot APIs are finalized 492 */ 493 public void setHotspot(int id, float x, float y) {} 494 495 /** 496 * Removes the specified hotspot from the drawable. 497 * 498 * @param id unique identifier for the hotspot 499 * @hide until hotspot APIs are finalized 500 */ 501 public void removeHotspot(int id) {} 502 503 /** 504 * Removes all hotspots from the drawable. 505 * 506 * @hide until hotspot APIs are finalized 507 */ 508 public void clearHotspots() {} 509 510 /** 511 * Indicates whether this view will change its appearance based on state. 512 * Clients can use this to determine whether it is necessary to calculate 513 * their state and call setState. 514 * 515 * @return True if this view changes its appearance based on state, false 516 * otherwise. 517 * 518 * @see #setState(int[]) 519 */ 520 public boolean isStateful() { 521 return false; 522 } 523 524 /** 525 * Specify a set of states for the drawable. These are use-case specific, 526 * so see the relevant documentation. As an example, the background for 527 * widgets like Button understand the following states: 528 * [{@link android.R.attr#state_focused}, 529 * {@link android.R.attr#state_pressed}]. 530 * 531 * <p>If the new state you are supplying causes the appearance of the 532 * Drawable to change, then it is responsible for calling 533 * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> 534 * true will be returned from this function. 535 * 536 * <p>Note: The Drawable holds a reference on to <var>stateSet</var> 537 * until a new state array is given to it, so you must not modify this 538 * array during that time.</p> 539 * 540 * @param stateSet The new set of states to be displayed. 541 * 542 * @return Returns true if this change in state has caused the appearance 543 * of the Drawable to change (hence requiring an invalidate), otherwise 544 * returns false. 545 */ 546 public boolean setState(final int[] stateSet) { 547 if (!Arrays.equals(mStateSet, stateSet)) { 548 mStateSet = stateSet; 549 return onStateChange(stateSet); 550 } 551 return false; 552 } 553 554 /** 555 * Describes the current state, as a union of primitve states, such as 556 * {@link android.R.attr#state_focused}, 557 * {@link android.R.attr#state_selected}, etc. 558 * Some drawables may modify their imagery based on the selected state. 559 * @return An array of resource Ids describing the current state. 560 */ 561 public int[] getState() { 562 return mStateSet; 563 } 564 565 /** 566 * If this Drawable does transition animations between states, ask that 567 * it immediately jump to the current state and skip any active animations. 568 */ 569 public void jumpToCurrentState() { 570 } 571 572 /** 573 * @return The current drawable that will be used by this drawable. For simple drawables, this 574 * is just the drawable itself. For drawables that change state like 575 * {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable 576 * currently in use. 577 */ 578 public Drawable getCurrent() { 579 return this; 580 } 581 582 /** 583 * Specify the level for the drawable. This allows a drawable to vary its 584 * imagery based on a continuous controller, for example to show progress 585 * or volume level. 586 * 587 * <p>If the new level you are supplying causes the appearance of the 588 * Drawable to change, then it is responsible for calling 589 * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> 590 * true will be returned from this function. 591 * 592 * @param level The new level, from 0 (minimum) to 10000 (maximum). 593 * 594 * @return Returns true if this change in level has caused the appearance 595 * of the Drawable to change (hence requiring an invalidate), otherwise 596 * returns false. 597 */ 598 public final boolean setLevel(int level) { 599 if (mLevel != level) { 600 mLevel = level; 601 return onLevelChange(level); 602 } 603 return false; 604 } 605 606 /** 607 * Retrieve the current level. 608 * 609 * @return int Current level, from 0 (minimum) to 10000 (maximum). 610 */ 611 public final int getLevel() { 612 return mLevel; 613 } 614 615 /** 616 * Set whether this Drawable is visible. This generally does not impact 617 * the Drawable's behavior, but is a hint that can be used by some 618 * Drawables, for example, to decide whether run animations. 619 * 620 * @param visible Set to true if visible, false if not. 621 * @param restart You can supply true here to force the drawable to behave 622 * as if it has just become visible, even if it had last 623 * been set visible. Used for example to force animations 624 * to restart. 625 * 626 * @return boolean Returns true if the new visibility is different than 627 * its previous state. 628 */ 629 public boolean setVisible(boolean visible, boolean restart) { 630 boolean changed = mVisible != visible; 631 if (changed) { 632 mVisible = visible; 633 invalidateSelf(); 634 } 635 return changed; 636 } 637 638 public final boolean isVisible() { 639 return mVisible; 640 } 641 642 /** 643 * Set whether this Drawable is automatically mirrored when its layout direction is RTL 644 * (right-to left). See {@link android.util.LayoutDirection}. 645 * 646 * @param mirrored Set to true if the Drawable should be mirrored, false if not. 647 */ 648 public void setAutoMirrored(boolean mirrored) { 649 } 650 651 /** 652 * Tells if this Drawable will be automatically mirrored when its layout direction is RTL 653 * right-to-left. See {@link android.util.LayoutDirection}. 654 * 655 * @return boolean Returns true if this Drawable will be automatically mirrored. 656 */ 657 public boolean isAutoMirrored() { 658 return false; 659 } 660 661 /** 662 * Return the opacity/transparency of this Drawable. The returned value is 663 * one of the abstract format constants in 664 * {@link android.graphics.PixelFormat}: 665 * {@link android.graphics.PixelFormat#UNKNOWN}, 666 * {@link android.graphics.PixelFormat#TRANSLUCENT}, 667 * {@link android.graphics.PixelFormat#TRANSPARENT}, or 668 * {@link android.graphics.PixelFormat#OPAQUE}. 669 * 670 * <p>Generally a Drawable should be as conservative as possible with the 671 * value it returns. For example, if it contains multiple child drawables 672 * and only shows one of them at a time, if only one of the children is 673 * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be 674 * returned. You can use the method {@link #resolveOpacity} to perform a 675 * standard reduction of two opacities to the appropriate single output. 676 * 677 * <p>Note that the returned value does <em>not</em> take into account a 678 * custom alpha or color filter that has been applied by the client through 679 * the {@link #setAlpha} or {@link #setColorFilter} methods. 680 * 681 * @return int The opacity class of the Drawable. 682 * 683 * @see android.graphics.PixelFormat 684 */ 685 public abstract int getOpacity(); 686 687 /** 688 * Return the appropriate opacity value for two source opacities. If 689 * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT, 690 * that is returned; else, if either is TRANSPARENT, that is returned; 691 * else, OPAQUE is returned. 692 * 693 * <p>This is to help in implementing {@link #getOpacity}. 694 * 695 * @param op1 One opacity value. 696 * @param op2 Another opacity value. 697 * 698 * @return int The combined opacity value. 699 * 700 * @see #getOpacity 701 */ 702 public static int resolveOpacity(int op1, int op2) { 703 if (op1 == op2) { 704 return op1; 705 } 706 if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) { 707 return PixelFormat.UNKNOWN; 708 } 709 if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) { 710 return PixelFormat.TRANSLUCENT; 711 } 712 if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) { 713 return PixelFormat.TRANSPARENT; 714 } 715 return PixelFormat.OPAQUE; 716 } 717 718 /** 719 * Returns a Region representing the part of the Drawable that is completely 720 * transparent. This can be used to perform drawing operations, identifying 721 * which parts of the target will not change when rendering the Drawable. 722 * The default implementation returns null, indicating no transparent 723 * region; subclasses can optionally override this to return an actual 724 * Region if they want to supply this optimization information, but it is 725 * not required that they do so. 726 * 727 * @return Returns null if the Drawables has no transparent region to 728 * report, else a Region holding the parts of the Drawable's bounds that 729 * are transparent. 730 */ 731 public Region getTransparentRegion() { 732 return null; 733 } 734 735 /** 736 * Override this in your subclass to change appearance if you recognize the 737 * specified state. 738 * 739 * @return Returns true if the state change has caused the appearance of 740 * the Drawable to change (that is, it needs to be drawn), else false 741 * if it looks the same and there is no need to redraw it since its 742 * last state. 743 */ 744 protected boolean onStateChange(int[] state) { return false; } 745 /** Override this in your subclass to change appearance if you vary based 746 * on level. 747 * @return Returns true if the level change has caused the appearance of 748 * the Drawable to change (that is, it needs to be drawn), else false 749 * if it looks the same and there is no need to redraw it since its 750 * last level. 751 */ 752 protected boolean onLevelChange(int level) { return false; } 753 /** 754 * Override this in your subclass to change appearance if you vary based on 755 * the bounds. 756 */ 757 protected void onBoundsChange(Rect bounds) {} 758 759 /** 760 * Return the intrinsic width of the underlying drawable object. Returns 761 * -1 if it has no intrinsic width, such as with a solid color. 762 */ 763 public int getIntrinsicWidth() { 764 return -1; 765 } 766 767 /** 768 * Return the intrinsic height of the underlying drawable object. Returns 769 * -1 if it has no intrinsic height, such as with a solid color. 770 */ 771 public int getIntrinsicHeight() { 772 return -1; 773 } 774 775 /** 776 * Returns the minimum width suggested by this Drawable. If a View uses this 777 * Drawable as a background, it is suggested that the View use at least this 778 * value for its width. (There will be some scenarios where this will not be 779 * possible.) This value should INCLUDE any padding. 780 * 781 * @return The minimum width suggested by this Drawable. If this Drawable 782 * doesn't have a suggested minimum width, 0 is returned. 783 */ 784 public int getMinimumWidth() { 785 final int intrinsicWidth = getIntrinsicWidth(); 786 return intrinsicWidth > 0 ? intrinsicWidth : 0; 787 } 788 789 /** 790 * Returns the minimum height suggested by this Drawable. If a View uses this 791 * Drawable as a background, it is suggested that the View use at least this 792 * value for its height. (There will be some scenarios where this will not be 793 * possible.) This value should INCLUDE any padding. 794 * 795 * @return The minimum height suggested by this Drawable. If this Drawable 796 * doesn't have a suggested minimum height, 0 is returned. 797 */ 798 public int getMinimumHeight() { 799 final int intrinsicHeight = getIntrinsicHeight(); 800 return intrinsicHeight > 0 ? intrinsicHeight : 0; 801 } 802 803 /** 804 * Return in padding the insets suggested by this Drawable for placing 805 * content inside the drawable's bounds. Positive values move toward the 806 * center of the Drawable (set Rect.inset). Returns true if this drawable 807 * actually has a padding, else false. When false is returned, the padding 808 * is always set to 0. 809 */ 810 public boolean getPadding(Rect padding) { 811 padding.set(0, 0, 0, 0); 812 return false; 813 } 814 815 /** 816 * Return in insets the layout insets suggested by this Drawable for use with alignment 817 * operations during layout. 818 * 819 * @hide 820 */ 821 public Insets getOpticalInsets() { 822 return Insets.NONE; 823 } 824 825 /** 826 * Make this drawable mutable. This operation cannot be reversed. A mutable 827 * drawable is guaranteed to not share its state with any other drawable. 828 * This is especially useful when you need to modify properties of drawables 829 * loaded from resources. By default, all drawables instances loaded from 830 * the same resource share a common state; if you modify the state of one 831 * instance, all the other instances will receive the same modification. 832 * 833 * Calling this method on a mutable Drawable will have no effect. 834 * 835 * @return This drawable. 836 * @see ConstantState 837 * @see #getConstantState() 838 */ 839 public Drawable mutate() { 840 return this; 841 } 842 843 /** 844 * Create a drawable from an inputstream 845 */ 846 public static Drawable createFromStream(InputStream is, String srcName) { 847 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 848 try { 849 return createFromResourceStream(null, null, is, srcName, null); 850 } finally { 851 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 852 } 853 } 854 855 /** 856 * Create a drawable from an inputstream, using the given resources and 857 * value to determine density information. 858 */ 859 public static Drawable createFromResourceStream(Resources res, TypedValue value, 860 InputStream is, String srcName) { 861 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 862 try { 863 return createFromResourceStream(res, value, is, srcName, null); 864 } finally { 865 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 866 } 867 } 868 869 /** 870 * Create a drawable from an inputstream, using the given resources and 871 * value to determine density information. 872 */ 873 public static Drawable createFromResourceStream(Resources res, TypedValue value, 874 InputStream is, String srcName, BitmapFactory.Options opts) { 875 876 if (is == null) { 877 return null; 878 } 879 880 /* ugh. The decodeStream contract is that we have already allocated 881 the pad rect, but if the bitmap does not had a ninepatch chunk, 882 then the pad will be ignored. If we could change this to lazily 883 alloc/assign the rect, we could avoid the GC churn of making new 884 Rects only to drop them on the floor. 885 */ 886 Rect pad = new Rect(); 887 888 // Special stuff for compatibility mode: if the target density is not 889 // the same as the display density, but the resource -is- the same as 890 // the display density, then don't scale it down to the target density. 891 // This allows us to load the system's density-correct resources into 892 // an application in compatibility mode, without scaling those down 893 // to the compatibility density only to have them scaled back up when 894 // drawn to the screen. 895 if (opts == null) opts = new BitmapFactory.Options(); 896 opts.inScreenDensity = res != null 897 ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE; 898 Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts); 899 if (bm != null) { 900 byte[] np = bm.getNinePatchChunk(); 901 if (np == null || !NinePatch.isNinePatchChunk(np)) { 902 np = null; 903 pad = null; 904 } 905 int[] layoutBounds = bm.getLayoutBounds(); 906 Rect layoutBoundsRect = null; 907 if (layoutBounds != null) { 908 layoutBoundsRect = new Rect(layoutBounds[0], layoutBounds[1], 909 layoutBounds[2], layoutBounds[3]); 910 } 911 return drawableFromBitmap(res, bm, np, pad, layoutBoundsRect, srcName); 912 } 913 return null; 914 } 915 916 /** 917 * Create a drawable from an XML document. For more information on how to 918 * create resources in XML, see 919 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. 920 */ 921 public static Drawable createFromXml(Resources r, XmlPullParser parser) 922 throws XmlPullParserException, IOException { 923 AttributeSet attrs = Xml.asAttributeSet(parser); 924 925 int type; 926 while ((type=parser.next()) != XmlPullParser.START_TAG && 927 type != XmlPullParser.END_DOCUMENT) { 928 // Empty loop 929 } 930 931 if (type != XmlPullParser.START_TAG) { 932 throw new XmlPullParserException("No start tag found"); 933 } 934 935 Drawable drawable = createFromXmlInner(r, parser, attrs); 936 937 if (drawable == null) { 938 throw new RuntimeException("Unknown initial tag: " + parser.getName()); 939 } 940 941 return drawable; 942 } 943 944 /** 945 * Create from inside an XML document. Called on a parser positioned at 946 * a tag in an XML document, tries to create a Drawable from that tag. 947 * Returns null if the tag is not a valid drawable. 948 */ 949 public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs) 950 throws XmlPullParserException, IOException { 951 Drawable drawable; 952 953 final String name = parser.getName(); 954 955 if (name.equals("selector")) { 956 drawable = new StateListDrawable(); 957 } else if (name.equals("level-list")) { 958 drawable = new LevelListDrawable(); 959 } else if (name.equals("layer-list")) { 960 drawable = new LayerDrawable(); 961 } else if (name.equals("transition")) { 962 drawable = new TransitionDrawable(); 963 } else if (name.equals("reveal")) { 964 drawable = new RevealDrawable(); 965 } else if (name.equals("color")) { 966 drawable = new ColorDrawable(); 967 } else if (name.equals("shape")) { 968 drawable = new GradientDrawable(); 969 } else if (name.equals("scale")) { 970 drawable = new ScaleDrawable(); 971 } else if (name.equals("clip")) { 972 drawable = new ClipDrawable(); 973 } else if (name.equals("rotate")) { 974 drawable = new RotateDrawable(); 975 } else if (name.equals("animated-rotate")) { 976 drawable = new AnimatedRotateDrawable(); 977 } else if (name.equals("animation-list")) { 978 drawable = new AnimationDrawable(); 979 } else if (name.equals("inset")) { 980 drawable = new InsetDrawable(); 981 } else if (name.equals("bitmap")) { 982 //noinspection deprecation 983 drawable = new BitmapDrawable(r); 984 if (r != null) { 985 ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 986 } 987 } else if (name.equals("nine-patch")) { 988 drawable = new NinePatchDrawable(); 989 if (r != null) { 990 ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 991 } 992 } else { 993 throw new XmlPullParserException(parser.getPositionDescription() + 994 ": invalid drawable tag " + name); 995 } 996 997 drawable.inflate(r, parser, attrs); 998 return drawable; 999 } 1000 1001 1002 /** 1003 * Create a drawable from file path name. 1004 */ 1005 public static Drawable createFromPath(String pathName) { 1006 if (pathName == null) { 1007 return null; 1008 } 1009 1010 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName); 1011 try { 1012 Bitmap bm = BitmapFactory.decodeFile(pathName); 1013 if (bm != null) { 1014 return drawableFromBitmap(null, bm, null, null, null, pathName); 1015 } 1016 } finally { 1017 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1018 } 1019 1020 return null; 1021 } 1022 1023 /** 1024 * Inflate this Drawable from an XML resource. 1025 */ 1026 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) 1027 throws XmlPullParserException, IOException { 1028 1029 TypedArray a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable); 1030 inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible); 1031 a.recycle(); 1032 } 1033 1034 /** 1035 * Inflate a Drawable from an XML resource. 1036 * 1037 * @throws XmlPullParserException 1038 * @throws IOException 1039 */ 1040 void inflateWithAttributes(Resources r, XmlPullParser parser, 1041 TypedArray attrs, int visibleAttr) 1042 throws XmlPullParserException, IOException { 1043 1044 mVisible = attrs.getBoolean(visibleAttr, mVisible); 1045 } 1046 1047 /** 1048 * This abstract class is used by {@link Drawable}s to store shared constant state and data 1049 * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance 1050 * share a unique bitmap stored in their ConstantState. 1051 * 1052 * <p> 1053 * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances 1054 * from this ConstantState. 1055 * </p> 1056 * 1057 * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling 1058 * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that 1059 * Drawable. 1060 */ 1061 public static abstract class ConstantState { 1062 /** 1063 * Create a new drawable without supplying resources the caller 1064 * is running in. Note that using this means the density-dependent 1065 * drawables (like bitmaps) will not be able to update their target 1066 * density correctly. One should use {@link #newDrawable(Resources)} 1067 * instead to provide a resource. 1068 */ 1069 public abstract Drawable newDrawable(); 1070 /** 1071 * Create a new Drawable instance from its constant state. This 1072 * must be implemented for drawables that change based on the target 1073 * density of their caller (that is depending on whether it is 1074 * in compatibility mode). 1075 */ 1076 public Drawable newDrawable(Resources res) { 1077 return newDrawable(); 1078 } 1079 /** 1080 * Return a bit mask of configuration changes that will impact 1081 * this drawable (and thus require completely reloading it). 1082 */ 1083 public abstract int getChangingConfigurations(); 1084 1085 /** 1086 * @hide 1087 */ 1088 public Bitmap getBitmap() { 1089 return null; 1090 } 1091 } 1092 1093 /** 1094 * Return a {@link ConstantState} instance that holds the shared state of this Drawable. 1095 * 1096 * @return The ConstantState associated to that Drawable. 1097 * @see ConstantState 1098 * @see Drawable#mutate() 1099 */ 1100 public ConstantState getConstantState() { 1101 return null; 1102 } 1103 1104 private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, 1105 Rect pad, Rect layoutBounds, String srcName) { 1106 1107 if (np != null) { 1108 return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName); 1109 } 1110 1111 return new BitmapDrawable(res, bm); 1112 } 1113 1114 /** 1115 * Parses a {@link android.graphics.PorterDuff.Mode} from a colorFilterMode 1116 * attribute's enum value. 1117 */ 1118 static PorterDuff.Mode parseColorFilterMode(int value) { 1119 final PorterDuff.Mode[] modes = PorterDuff.Mode.values(); 1120 if (value >= 0 && value < modes.length) { 1121 return modes[value]; 1122 } 1123 return null; 1124 } 1125} 1126 1127