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