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