Drawable.java revision 77b5cad3efedd20f2b7cc14d87ccce1b0261960a
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 of 0 alpha. 865 * Subclasses that wish to convey a different shape or alpha value must override this method. 866 * 867 * @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider) 868 */ 869 public void getOutline(@NonNull Outline outline) { 870 outline.setRect(getBounds()); 871 outline.setAlpha(getAlpha() / 255.0f); 872 } 873 874 /** 875 * Make this drawable mutable. This operation cannot be reversed. A mutable 876 * drawable is guaranteed to not share its state with any other drawable. 877 * This is especially useful when you need to modify properties of drawables 878 * loaded from resources. By default, all drawables instances loaded from 879 * the same resource share a common state; if you modify the state of one 880 * instance, all the other instances will receive the same modification. 881 * 882 * Calling this method on a mutable Drawable will have no effect. 883 * 884 * @return This drawable. 885 * @see ConstantState 886 * @see #getConstantState() 887 */ 888 public Drawable mutate() { 889 return this; 890 } 891 892 /** 893 * Create a drawable from an inputstream 894 */ 895 public static Drawable createFromStream(InputStream is, String srcName) { 896 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 897 try { 898 return createFromResourceStream(null, null, is, srcName); 899 } finally { 900 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 901 } 902 } 903 904 /** 905 * Create a drawable from an inputstream, using the given resources and 906 * value to determine density information. 907 */ 908 public static Drawable createFromResourceStream(Resources res, TypedValue value, 909 InputStream is, String srcName) { 910 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 911 try { 912 return createFromResourceStream(res, value, is, srcName, null); 913 } finally { 914 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 915 } 916 } 917 918 /** 919 * Create a drawable from an inputstream, using the given resources and 920 * value to determine density information. 921 */ 922 public static Drawable createFromResourceStream(Resources res, TypedValue value, 923 InputStream is, String srcName, BitmapFactory.Options opts) { 924 if (is == null) { 925 return null; 926 } 927 928 /* ugh. The decodeStream contract is that we have already allocated 929 the pad rect, but if the bitmap does not had a ninepatch chunk, 930 then the pad will be ignored. If we could change this to lazily 931 alloc/assign the rect, we could avoid the GC churn of making new 932 Rects only to drop them on the floor. 933 */ 934 Rect pad = new Rect(); 935 936 // Special stuff for compatibility mode: if the target density is not 937 // the same as the display density, but the resource -is- the same as 938 // the display density, then don't scale it down to the target density. 939 // This allows us to load the system's density-correct resources into 940 // an application in compatibility mode, without scaling those down 941 // to the compatibility density only to have them scaled back up when 942 // drawn to the screen. 943 if (opts == null) opts = new BitmapFactory.Options(); 944 opts.inScreenDensity = res != null 945 ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE; 946 Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts); 947 if (bm != null) { 948 byte[] np = bm.getNinePatchChunk(); 949 if (np == null || !NinePatch.isNinePatchChunk(np)) { 950 np = null; 951 pad = null; 952 } 953 954 final Rect opticalInsets = new Rect(); 955 bm.getOpticalInsets(opticalInsets); 956 return drawableFromBitmap(res, bm, np, pad, opticalInsets, srcName); 957 } 958 return null; 959 } 960 961 /** 962 * Create a drawable from an XML document. For more information on how to 963 * create resources in XML, see 964 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. 965 */ 966 public static Drawable createFromXml(Resources r, XmlPullParser parser) 967 throws XmlPullParserException, IOException { 968 return createFromXml(r, parser, null); 969 } 970 971 /** 972 * Create a drawable from an XML document using an optional {@link Theme}. 973 * For more information on how to create resources in XML, see 974 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. 975 */ 976 public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme) 977 throws XmlPullParserException, IOException { 978 AttributeSet attrs = Xml.asAttributeSet(parser); 979 980 int type; 981 while ((type=parser.next()) != XmlPullParser.START_TAG && 982 type != XmlPullParser.END_DOCUMENT) { 983 // Empty loop 984 } 985 986 if (type != XmlPullParser.START_TAG) { 987 throw new XmlPullParserException("No start tag found"); 988 } 989 990 Drawable drawable = createFromXmlInner(r, parser, attrs, theme); 991 992 if (drawable == null) { 993 throw new RuntimeException("Unknown initial tag: " + parser.getName()); 994 } 995 996 return drawable; 997 } 998 999 /** 1000 * Create from inside an XML document. Called on a parser positioned at 1001 * a tag in an XML document, tries to create a Drawable from that tag. 1002 * Returns null if the tag is not a valid drawable. 1003 */ 1004 public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs) 1005 throws XmlPullParserException, IOException { 1006 return createFromXmlInner(r, parser, attrs, null); 1007 } 1008 1009 /** 1010 * Create a drawable from inside an XML document using an optional 1011 * {@link Theme}. Called on a parser positioned at a tag in an XML 1012 * document, tries to create a Drawable from that tag. Returns {@code null} 1013 * if the tag is not a valid drawable. 1014 */ 1015 public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs, 1016 Theme theme) throws XmlPullParserException, IOException { 1017 final Drawable drawable; 1018 1019 final String name = parser.getName(); 1020 if (name.equals("selector")) { 1021 drawable = new StateListDrawable(); 1022 } else if (name.equals("animated-selector")) { 1023 drawable = new AnimatedStateListDrawable(); 1024 } else if (name.equals("level-list")) { 1025 drawable = new LevelListDrawable(); 1026 } else if (name.equals("layer-list")) { 1027 drawable = new LayerDrawable(); 1028 } else if (name.equals("transition")) { 1029 drawable = new TransitionDrawable(); 1030 } else if (name.equals("ripple")) { 1031 drawable = new RippleDrawable(); 1032 } else if (name.equals("color")) { 1033 drawable = new ColorDrawable(); 1034 } else if (name.equals("shape")) { 1035 drawable = new GradientDrawable(); 1036 } else if (name.equals("vector")) { 1037 drawable = new VectorDrawable(); 1038 } else if (name.equals("animated-vector")) { 1039 drawable = new AnimatedVectorDrawable(); 1040 } else if (name.equals("scale")) { 1041 drawable = new ScaleDrawable(); 1042 } else if (name.equals("clip")) { 1043 drawable = new ClipDrawable(); 1044 } else if (name.equals("rotate")) { 1045 drawable = new RotateDrawable(); 1046 } else if (name.equals("animated-rotate")) { 1047 drawable = new AnimatedRotateDrawable(); 1048 } else if (name.equals("animation-list")) { 1049 drawable = new AnimationDrawable(); 1050 } else if (name.equals("inset")) { 1051 drawable = new InsetDrawable(); 1052 } else if (name.equals("bitmap")) { 1053 //noinspection deprecation 1054 drawable = new BitmapDrawable(r); 1055 if (r != null) { 1056 ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 1057 } 1058 } else if (name.equals("nine-patch")) { 1059 drawable = new NinePatchDrawable(); 1060 if (r != null) { 1061 ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 1062 } 1063 } else { 1064 throw new XmlPullParserException(parser.getPositionDescription() + 1065 ": invalid drawable tag " + name); 1066 } 1067 1068 drawable.inflate(r, parser, attrs, theme); 1069 return drawable; 1070 } 1071 1072 1073 /** 1074 * Create a drawable from file path name. 1075 */ 1076 public static Drawable createFromPath(String pathName) { 1077 if (pathName == null) { 1078 return null; 1079 } 1080 1081 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName); 1082 try { 1083 Bitmap bm = BitmapFactory.decodeFile(pathName); 1084 if (bm != null) { 1085 return drawableFromBitmap(null, bm, null, null, null, pathName); 1086 } 1087 } finally { 1088 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1089 } 1090 1091 return null; 1092 } 1093 1094 /** 1095 * Inflate this Drawable from an XML resource. Does not apply a theme. 1096 * 1097 * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme) 1098 */ 1099 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) 1100 throws XmlPullParserException, IOException { 1101 inflate(r, parser, attrs, null); 1102 } 1103 1104 /** 1105 * Inflate this Drawable from an XML resource optionally styled by a theme. 1106 * 1107 * @param r Resources used to resolve attribute values 1108 * @param parser XML parser from which to inflate this Drawable 1109 * @param attrs Base set of attribute values 1110 * @param theme Theme to apply, may be null 1111 * @throws XmlPullParserException 1112 * @throws IOException 1113 */ 1114 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 1115 throws XmlPullParserException, IOException { 1116 final TypedArray a; 1117 if (theme != null) { 1118 a = theme.obtainStyledAttributes( 1119 attrs, com.android.internal.R.styleable.Drawable, 0, 0); 1120 } else { 1121 a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable); 1122 } 1123 1124 inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible); 1125 a.recycle(); 1126 } 1127 1128 /** 1129 * Inflate a Drawable from an XML resource. 1130 * 1131 * @throws XmlPullParserException 1132 * @throws IOException 1133 */ 1134 void inflateWithAttributes(Resources r, XmlPullParser parser, TypedArray attrs, int visibleAttr) 1135 throws XmlPullParserException, IOException { 1136 mVisible = attrs.getBoolean(visibleAttr, mVisible); 1137 } 1138 1139 /** 1140 * This abstract class is used by {@link Drawable}s to store shared constant state and data 1141 * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance 1142 * share a unique bitmap stored in their ConstantState. 1143 * 1144 * <p> 1145 * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances 1146 * from this ConstantState. 1147 * </p> 1148 * 1149 * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling 1150 * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that 1151 * Drawable. 1152 */ 1153 public static abstract class ConstantState { 1154 /** 1155 * Create a new drawable without supplying resources the caller 1156 * is running in. Note that using this means the density-dependent 1157 * drawables (like bitmaps) will not be able to update their target 1158 * density correctly. One should use {@link #newDrawable(Resources)} 1159 * instead to provide a resource. 1160 */ 1161 public abstract Drawable newDrawable(); 1162 1163 /** 1164 * Create a new Drawable instance from its constant state. This 1165 * must be implemented for drawables that change based on the target 1166 * density of their caller (that is depending on whether it is 1167 * in compatibility mode). 1168 */ 1169 public Drawable newDrawable(Resources res) { 1170 return newDrawable(); 1171 } 1172 1173 /** 1174 * Create a new Drawable instance from its constant state. This must be 1175 * implemented for drawables that can have a theme applied. 1176 */ 1177 public Drawable newDrawable(Resources res, Theme theme) { 1178 return newDrawable(); 1179 } 1180 1181 /** 1182 * Return a bit mask of configuration changes that will impact 1183 * this drawable (and thus require completely reloading it). 1184 */ 1185 public abstract int getChangingConfigurations(); 1186 1187 /** 1188 * @hide 1189 */ 1190 public Bitmap getBitmap() { 1191 return null; 1192 } 1193 1194 /** 1195 * Return whether this constant state can have a theme applied. 1196 */ 1197 public boolean canApplyTheme() { 1198 return false; 1199 } 1200 } 1201 1202 /** 1203 * Return a {@link ConstantState} instance that holds the shared state of this Drawable. 1204 * 1205 * @return The ConstantState associated to that Drawable. 1206 * @see ConstantState 1207 * @see Drawable#mutate() 1208 */ 1209 public ConstantState getConstantState() { 1210 return null; 1211 } 1212 1213 private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, 1214 Rect pad, Rect layoutBounds, String srcName) { 1215 1216 if (np != null) { 1217 return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName); 1218 } 1219 1220 return new BitmapDrawable(res, bm); 1221 } 1222 1223 /** 1224 * Ensures the tint filter is consistent with the current tint color and 1225 * mode. 1226 */ 1227 PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint, 1228 PorterDuff.Mode tintMode) { 1229 if (tint == null || tintMode == null) { 1230 return null; 1231 } 1232 1233 final int color = tint.getColorForState(getState(), Color.TRANSPARENT); 1234 if (tintFilter == null) { 1235 return new PorterDuffColorFilter(color, tintMode); 1236 } 1237 1238 tintFilter.setColor(color); 1239 tintFilter.setMode(tintMode); 1240 return tintFilter; 1241 } 1242 1243 /** 1244 * Obtains styled attributes from the theme, if available, or unstyled 1245 * resources if the theme is null. 1246 */ 1247 static TypedArray obtainAttributes( 1248 Resources res, Theme theme, AttributeSet set, int[] attrs) { 1249 if (theme == null) { 1250 return res.obtainAttributes(set, attrs); 1251 } 1252 return theme.obtainStyledAttributes(set, attrs, 0, 0); 1253 } 1254 1255 /** 1256 * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode 1257 * attribute's enum value. 1258 * 1259 * @hide 1260 */ 1261 public static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) { 1262 switch (value) { 1263 case 3: return Mode.SRC_OVER; 1264 case 5: return Mode.SRC_IN; 1265 case 9: return Mode.SRC_ATOP; 1266 case 14: return Mode.MULTIPLY; 1267 case 15: return Mode.SCREEN; 1268 case 16: return Mode.ADD; 1269 default: return defaultMode; 1270 } 1271 } 1272} 1273 1274