Drawable.java revision 9a347f199284ad8bcb8a81bfbd306fe0b1a710ba
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.res.Configuration}. 242 * 243 * @see android.content.res.Configuration 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.res.Configuration}. 259 * 260 * @see android.content.res.Configuration 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 /** 520 * Whether this drawable requests projection. 521 * 522 * @hide magic! 523 */ 524 public boolean isProjected() { 525 return false; 526 } 527 528 /** 529 * Indicates whether this drawable will change its appearance based on 530 * state. Clients can use this to determine whether it is necessary to 531 * calculate their state and call setState. 532 * 533 * @return True if this drawable changes its appearance based on state, 534 * false otherwise. 535 * @see #setState(int[]) 536 */ 537 public boolean isStateful() { 538 return false; 539 } 540 541 /** 542 * Specify a set of states for the drawable. These are use-case specific, 543 * so see the relevant documentation. As an example, the background for 544 * widgets like Button understand the following states: 545 * [{@link android.R.attr#state_focused}, 546 * {@link android.R.attr#state_pressed}]. 547 * 548 * <p>If the new state you are supplying causes the appearance of the 549 * Drawable to change, then it is responsible for calling 550 * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> 551 * true will be returned from this function. 552 * 553 * <p>Note: The Drawable holds a reference on to <var>stateSet</var> 554 * until a new state array is given to it, so you must not modify this 555 * array during that time.</p> 556 * 557 * @param stateSet The new set of states to be displayed. 558 * 559 * @return Returns true if this change in state has caused the appearance 560 * of the Drawable to change (hence requiring an invalidate), otherwise 561 * returns false. 562 */ 563 public boolean setState(final int[] stateSet) { 564 if (!Arrays.equals(mStateSet, stateSet)) { 565 mStateSet = stateSet; 566 return onStateChange(stateSet); 567 } 568 return false; 569 } 570 571 /** 572 * Describes the current state, as a union of primitve states, such as 573 * {@link android.R.attr#state_focused}, 574 * {@link android.R.attr#state_selected}, etc. 575 * Some drawables may modify their imagery based on the selected state. 576 * @return An array of resource Ids describing the current state. 577 */ 578 public int[] getState() { 579 return mStateSet; 580 } 581 582 /** 583 * If this Drawable does transition animations between states, ask that 584 * it immediately jump to the current state and skip any active animations. 585 */ 586 public void jumpToCurrentState() { 587 } 588 589 /** 590 * @return The current drawable that will be used by this drawable. For simple drawables, this 591 * is just the drawable itself. For drawables that change state like 592 * {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable 593 * currently in use. 594 */ 595 public Drawable getCurrent() { 596 return this; 597 } 598 599 /** 600 * Specify the level for the drawable. This allows a drawable to vary its 601 * imagery based on a continuous controller, for example to show progress 602 * or volume level. 603 * 604 * <p>If the new level you are supplying causes the appearance of the 605 * Drawable to change, then it is responsible for calling 606 * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em> 607 * true will be returned from this function. 608 * 609 * @param level The new level, from 0 (minimum) to 10000 (maximum). 610 * 611 * @return Returns true if this change in level has caused the appearance 612 * of the Drawable to change (hence requiring an invalidate), otherwise 613 * returns false. 614 */ 615 public final boolean setLevel(int level) { 616 if (mLevel != level) { 617 mLevel = level; 618 return onLevelChange(level); 619 } 620 return false; 621 } 622 623 /** 624 * Retrieve the current level. 625 * 626 * @return int Current level, from 0 (minimum) to 10000 (maximum). 627 */ 628 public final int getLevel() { 629 return mLevel; 630 } 631 632 /** 633 * Set whether this Drawable is visible. This generally does not impact 634 * the Drawable's behavior, but is a hint that can be used by some 635 * Drawables, for example, to decide whether run animations. 636 * 637 * @param visible Set to true if visible, false if not. 638 * @param restart You can supply true here to force the drawable to behave 639 * as if it has just become visible, even if it had last 640 * been set visible. Used for example to force animations 641 * to restart. 642 * 643 * @return boolean Returns true if the new visibility is different than 644 * its previous state. 645 */ 646 public boolean setVisible(boolean visible, boolean restart) { 647 boolean changed = mVisible != visible; 648 if (changed) { 649 mVisible = visible; 650 invalidateSelf(); 651 } 652 return changed; 653 } 654 655 public final boolean isVisible() { 656 return mVisible; 657 } 658 659 /** 660 * Set whether this Drawable is automatically mirrored when its layout direction is RTL 661 * (right-to left). See {@link android.util.LayoutDirection}. 662 * 663 * @param mirrored Set to true if the Drawable should be mirrored, false if not. 664 */ 665 public void setAutoMirrored(boolean mirrored) { 666 } 667 668 /** 669 * Tells if this Drawable will be automatically mirrored when its layout direction is RTL 670 * right-to-left. See {@link android.util.LayoutDirection}. 671 * 672 * @return boolean Returns true if this Drawable will be automatically mirrored. 673 */ 674 public boolean isAutoMirrored() { 675 return false; 676 } 677 678 /** 679 * Applies the specified theme to this Drawable and its children. 680 */ 681 public void applyTheme(@SuppressWarnings("unused") Theme t) { 682 } 683 684 public boolean canApplyTheme() { 685 return false; 686 } 687 688 /** 689 * Return the opacity/transparency of this Drawable. The returned value is 690 * one of the abstract format constants in 691 * {@link android.graphics.PixelFormat}: 692 * {@link android.graphics.PixelFormat#UNKNOWN}, 693 * {@link android.graphics.PixelFormat#TRANSLUCENT}, 694 * {@link android.graphics.PixelFormat#TRANSPARENT}, or 695 * {@link android.graphics.PixelFormat#OPAQUE}. 696 * 697 * <p>Generally a Drawable should be as conservative as possible with the 698 * value it returns. For example, if it contains multiple child drawables 699 * and only shows one of them at a time, if only one of the children is 700 * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be 701 * returned. You can use the method {@link #resolveOpacity} to perform a 702 * standard reduction of two opacities to the appropriate single output. 703 * 704 * <p>Note that the returned value does <em>not</em> take into account a 705 * custom alpha or color filter that has been applied by the client through 706 * the {@link #setAlpha} or {@link #setColorFilter} methods. 707 * 708 * @return int The opacity class of the Drawable. 709 * 710 * @see android.graphics.PixelFormat 711 */ 712 public abstract int getOpacity(); 713 714 /** 715 * Return the appropriate opacity value for two source opacities. If 716 * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT, 717 * that is returned; else, if either is TRANSPARENT, that is returned; 718 * else, OPAQUE is returned. 719 * 720 * <p>This is to help in implementing {@link #getOpacity}. 721 * 722 * @param op1 One opacity value. 723 * @param op2 Another opacity value. 724 * 725 * @return int The combined opacity value. 726 * 727 * @see #getOpacity 728 */ 729 public static int resolveOpacity(int op1, int op2) { 730 if (op1 == op2) { 731 return op1; 732 } 733 if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) { 734 return PixelFormat.UNKNOWN; 735 } 736 if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) { 737 return PixelFormat.TRANSLUCENT; 738 } 739 if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) { 740 return PixelFormat.TRANSPARENT; 741 } 742 return PixelFormat.OPAQUE; 743 } 744 745 /** 746 * Returns a Region representing the part of the Drawable that is completely 747 * transparent. This can be used to perform drawing operations, identifying 748 * which parts of the target will not change when rendering the Drawable. 749 * The default implementation returns null, indicating no transparent 750 * region; subclasses can optionally override this to return an actual 751 * Region if they want to supply this optimization information, but it is 752 * not required that they do so. 753 * 754 * @return Returns null if the Drawables has no transparent region to 755 * report, else a Region holding the parts of the Drawable's bounds that 756 * are transparent. 757 */ 758 public Region getTransparentRegion() { 759 return null; 760 } 761 762 /** 763 * Override this in your subclass to change appearance if you recognize the 764 * specified state. 765 * 766 * @return Returns true if the state change has caused the appearance of 767 * the Drawable to change (that is, it needs to be drawn), else false 768 * if it looks the same and there is no need to redraw it since its 769 * last state. 770 */ 771 protected boolean onStateChange(int[] state) { return false; } 772 /** Override this in your subclass to change appearance if you vary based 773 * on level. 774 * @return Returns true if the level change has caused the appearance of 775 * the Drawable to change (that is, it needs to be drawn), else false 776 * if it looks the same and there is no need to redraw it since its 777 * last level. 778 */ 779 protected boolean onLevelChange(int level) { return false; } 780 /** 781 * Override this in your subclass to change appearance if you vary based on 782 * the bounds. 783 */ 784 protected void onBoundsChange(Rect bounds) {} 785 786 /** 787 * Return the intrinsic width of the underlying drawable object. Returns 788 * -1 if it has no intrinsic width, such as with a solid color. 789 */ 790 public int getIntrinsicWidth() { 791 return -1; 792 } 793 794 /** 795 * Return the intrinsic height of the underlying drawable object. Returns 796 * -1 if it has no intrinsic height, such as with a solid color. 797 */ 798 public int getIntrinsicHeight() { 799 return -1; 800 } 801 802 /** 803 * Returns the minimum width suggested by this Drawable. If a View uses this 804 * Drawable as a background, it is suggested that the View use at least this 805 * value for its width. (There will be some scenarios where this will not be 806 * possible.) This value should INCLUDE any padding. 807 * 808 * @return The minimum width suggested by this Drawable. If this Drawable 809 * doesn't have a suggested minimum width, 0 is returned. 810 */ 811 public int getMinimumWidth() { 812 final int intrinsicWidth = getIntrinsicWidth(); 813 return intrinsicWidth > 0 ? intrinsicWidth : 0; 814 } 815 816 /** 817 * Returns the minimum height suggested by this Drawable. If a View uses this 818 * Drawable as a background, it is suggested that the View use at least this 819 * value for its height. (There will be some scenarios where this will not be 820 * possible.) This value should INCLUDE any padding. 821 * 822 * @return The minimum height suggested by this Drawable. If this Drawable 823 * doesn't have a suggested minimum height, 0 is returned. 824 */ 825 public int getMinimumHeight() { 826 final int intrinsicHeight = getIntrinsicHeight(); 827 return intrinsicHeight > 0 ? intrinsicHeight : 0; 828 } 829 830 /** 831 * Return in padding the insets suggested by this Drawable for placing 832 * content inside the drawable's bounds. Positive values move toward the 833 * center of the Drawable (set Rect.inset). 834 * 835 * @return true if this drawable actually has a padding, else false. When false is returned, 836 * the padding is always set to 0. 837 */ 838 public boolean getPadding(@NonNull Rect padding) { 839 padding.set(0, 0, 0, 0); 840 return false; 841 } 842 843 /** 844 * Return in insets the layout insets suggested by this Drawable for use with alignment 845 * operations during layout. 846 * 847 * @hide 848 */ 849 public Insets getOpticalInsets() { 850 return Insets.NONE; 851 } 852 853 /** 854 * Called to get the drawable to populate the Outline that defines its drawing area. 855 * <p> 856 * This method is called by the default {@link android.view.ViewOutlineProvider} to define 857 * the outline of the View. 858 * <p> 859 * The default behavior defines the outline to be the bounding rectangle. Subclasses that wish 860 * to convey a different shape must override this method. 861 * 862 * @return true if this drawable actually has an outline, else false. The outline must be 863 * populated by the drawable if true is returned. 864 * 865 * @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider) 866 */ 867 public boolean getOutline(@NonNull Outline outline) { 868 outline.setRect(getBounds()); 869 return true; 870 } 871 872 /** 873 * Make this drawable mutable. This operation cannot be reversed. A mutable 874 * drawable is guaranteed to not share its state with any other drawable. 875 * This is especially useful when you need to modify properties of drawables 876 * loaded from resources. By default, all drawables instances loaded from 877 * the same resource share a common state; if you modify the state of one 878 * instance, all the other instances will receive the same modification. 879 * 880 * Calling this method on a mutable Drawable will have no effect. 881 * 882 * @return This drawable. 883 * @see ConstantState 884 * @see #getConstantState() 885 */ 886 public Drawable mutate() { 887 return this; 888 } 889 890 /** 891 * Create a drawable from an inputstream 892 */ 893 public static Drawable createFromStream(InputStream is, String srcName) { 894 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 895 try { 896 return createFromResourceStream(null, null, is, srcName); 897 } finally { 898 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 899 } 900 } 901 902 /** 903 * Create a drawable from an inputstream, using the given resources and 904 * value to determine density information. 905 */ 906 public static Drawable createFromResourceStream(Resources res, TypedValue value, 907 InputStream is, String srcName) { 908 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable"); 909 try { 910 return createFromResourceStream(res, value, is, srcName, null); 911 } finally { 912 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 913 } 914 } 915 916 /** 917 * Create a drawable from an inputstream, using the given resources and 918 * value to determine density information. 919 */ 920 public static Drawable createFromResourceStream(Resources res, TypedValue value, 921 InputStream is, String srcName, BitmapFactory.Options opts) { 922 if (is == null) { 923 return null; 924 } 925 926 /* ugh. The decodeStream contract is that we have already allocated 927 the pad rect, but if the bitmap does not had a ninepatch chunk, 928 then the pad will be ignored. If we could change this to lazily 929 alloc/assign the rect, we could avoid the GC churn of making new 930 Rects only to drop them on the floor. 931 */ 932 Rect pad = new Rect(); 933 934 // Special stuff for compatibility mode: if the target density is not 935 // the same as the display density, but the resource -is- the same as 936 // the display density, then don't scale it down to the target density. 937 // This allows us to load the system's density-correct resources into 938 // an application in compatibility mode, without scaling those down 939 // to the compatibility density only to have them scaled back up when 940 // drawn to the screen. 941 if (opts == null) opts = new BitmapFactory.Options(); 942 opts.inScreenDensity = res != null 943 ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE; 944 Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts); 945 if (bm != null) { 946 byte[] np = bm.getNinePatchChunk(); 947 if (np == null || !NinePatch.isNinePatchChunk(np)) { 948 np = null; 949 pad = null; 950 } 951 int[] layoutBounds = bm.getLayoutBounds(); 952 Rect layoutBoundsRect = null; 953 if (layoutBounds != null) { 954 layoutBoundsRect = new Rect(layoutBounds[0], layoutBounds[1], 955 layoutBounds[2], layoutBounds[3]); 956 } 957 return drawableFromBitmap(res, bm, np, pad, layoutBoundsRect, srcName); 958 } 959 return null; 960 } 961 962 /** 963 * Create a drawable from an XML document. For more information on how to 964 * create resources in XML, see 965 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. 966 */ 967 public static Drawable createFromXml(Resources r, XmlPullParser parser) 968 throws XmlPullParserException, IOException { 969 return createFromXml(r, parser, null); 970 } 971 972 /** 973 * Create a drawable from an XML document using an optional {@link Theme}. 974 * For more information on how to create resources in XML, see 975 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>. 976 */ 977 public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme) 978 throws XmlPullParserException, IOException { 979 AttributeSet attrs = Xml.asAttributeSet(parser); 980 981 int type; 982 while ((type=parser.next()) != XmlPullParser.START_TAG && 983 type != XmlPullParser.END_DOCUMENT) { 984 // Empty loop 985 } 986 987 if (type != XmlPullParser.START_TAG) { 988 throw new XmlPullParserException("No start tag found"); 989 } 990 991 Drawable drawable = createFromXmlInner(r, parser, attrs, theme); 992 993 if (drawable == null) { 994 throw new RuntimeException("Unknown initial tag: " + parser.getName()); 995 } 996 997 return drawable; 998 } 999 1000 /** 1001 * Create from inside an XML document. Called on a parser positioned at 1002 * a tag in an XML document, tries to create a Drawable from that tag. 1003 * Returns null if the tag is not a valid drawable. 1004 */ 1005 public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs) 1006 throws XmlPullParserException, IOException { 1007 return createFromXmlInner(r, parser, attrs, null); 1008 } 1009 1010 /** 1011 * Create a drawable from inside an XML document using an optional 1012 * {@link Theme}. Called on a parser positioned at a tag in an XML 1013 * document, tries to create a Drawable from that tag. Returns {@code null} 1014 * if the tag is not a valid drawable. 1015 */ 1016 public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs, 1017 Theme theme) throws XmlPullParserException, IOException { 1018 final Drawable drawable; 1019 1020 final String name = parser.getName(); 1021 if (name.equals("selector")) { 1022 drawable = new StateListDrawable(); 1023 } else if (name.equals("animated-selector")) { 1024 drawable = new AnimatedStateListDrawable(); 1025 } else if (name.equals("material-progress")) { 1026 // TODO: Replace this with something less ridiculous. 1027 drawable = new MaterialProgressDrawable(); 1028 } else if (name.equals("level-list")) { 1029 drawable = new LevelListDrawable(); 1030 } else if (name.equals("layer-list")) { 1031 drawable = new LayerDrawable(); 1032 } else if (name.equals("transition")) { 1033 drawable = new TransitionDrawable(); 1034 } else if (name.equals("ripple")) { 1035 drawable = new RippleDrawable(); 1036 } else if (name.equals("color")) { 1037 drawable = new ColorDrawable(); 1038 } else if (name.equals("shape")) { 1039 drawable = new GradientDrawable(); 1040 } else if (name.equals("vector")) { 1041 drawable = new VectorDrawable(); 1042 } else if (name.equals("animated-vector")) { 1043 drawable = new AnimatedVectorDrawable(); 1044 } else if (name.equals("scale")) { 1045 drawable = new ScaleDrawable(); 1046 } else if (name.equals("clip")) { 1047 drawable = new ClipDrawable(); 1048 } else if (name.equals("rotate")) { 1049 drawable = new RotateDrawable(); 1050 } else if (name.equals("animated-rotate")) { 1051 drawable = new AnimatedRotateDrawable(); 1052 } else if (name.equals("animation-list")) { 1053 drawable = new AnimationDrawable(); 1054 } else if (name.equals("inset")) { 1055 drawable = new InsetDrawable(); 1056 } else if (name.equals("bitmap")) { 1057 //noinspection deprecation 1058 drawable = new BitmapDrawable(r); 1059 if (r != null) { 1060 ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 1061 } 1062 } else if (name.equals("nine-patch")) { 1063 drawable = new NinePatchDrawable(); 1064 if (r != null) { 1065 ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics()); 1066 } 1067 } else { 1068 throw new XmlPullParserException(parser.getPositionDescription() + 1069 ": invalid drawable tag " + name); 1070 } 1071 1072 drawable.inflate(r, parser, attrs, theme); 1073 return drawable; 1074 } 1075 1076 1077 /** 1078 * Create a drawable from file path name. 1079 */ 1080 public static Drawable createFromPath(String pathName) { 1081 if (pathName == null) { 1082 return null; 1083 } 1084 1085 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName); 1086 try { 1087 Bitmap bm = BitmapFactory.decodeFile(pathName); 1088 if (bm != null) { 1089 return drawableFromBitmap(null, bm, null, null, null, pathName); 1090 } 1091 } finally { 1092 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1093 } 1094 1095 return null; 1096 } 1097 1098 /** 1099 * Inflate this Drawable from an XML resource. Does not apply a theme. 1100 * 1101 * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme) 1102 */ 1103 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) 1104 throws XmlPullParserException, IOException { 1105 inflate(r, parser, attrs, null); 1106 } 1107 1108 /** 1109 * Inflate this Drawable from an XML resource optionally styled by a theme. 1110 * 1111 * @param r Resources used to resolve attribute values 1112 * @param parser XML parser from which to inflate this Drawable 1113 * @param attrs Base set of attribute values 1114 * @param theme Theme to apply, may be null 1115 * @throws XmlPullParserException 1116 * @throws IOException 1117 */ 1118 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 1119 throws XmlPullParserException, IOException { 1120 final TypedArray a; 1121 if (theme != null) { 1122 a = theme.obtainStyledAttributes( 1123 attrs, com.android.internal.R.styleable.Drawable, 0, 0); 1124 } else { 1125 a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable); 1126 } 1127 1128 inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible); 1129 a.recycle(); 1130 } 1131 1132 /** 1133 * Inflate a Drawable from an XML resource. 1134 * 1135 * @throws XmlPullParserException 1136 * @throws IOException 1137 */ 1138 void inflateWithAttributes(Resources r, XmlPullParser parser, TypedArray attrs, int visibleAttr) 1139 throws XmlPullParserException, IOException { 1140 mVisible = attrs.getBoolean(visibleAttr, mVisible); 1141 } 1142 1143 /** 1144 * This abstract class is used by {@link Drawable}s to store shared constant state and data 1145 * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance 1146 * share a unique bitmap stored in their ConstantState. 1147 * 1148 * <p> 1149 * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances 1150 * from this ConstantState. 1151 * </p> 1152 * 1153 * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling 1154 * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that 1155 * Drawable. 1156 */ 1157 public static abstract class ConstantState { 1158 /** 1159 * Create a new drawable without supplying resources the caller 1160 * is running in. Note that using this means the density-dependent 1161 * drawables (like bitmaps) will not be able to update their target 1162 * density correctly. One should use {@link #newDrawable(Resources)} 1163 * instead to provide a resource. 1164 */ 1165 public abstract Drawable newDrawable(); 1166 1167 /** 1168 * Create a new Drawable instance from its constant state. This 1169 * must be implemented for drawables that change based on the target 1170 * density of their caller (that is depending on whether it is 1171 * in compatibility mode). 1172 */ 1173 public Drawable newDrawable(Resources res) { 1174 return newDrawable(); 1175 } 1176 1177 /** 1178 * Create a new Drawable instance from its constant state. This must be 1179 * implemented for drawables that can have a theme applied. 1180 */ 1181 public Drawable newDrawable(Resources res, Theme theme) { 1182 return newDrawable(); 1183 } 1184 1185 /** 1186 * Return a bit mask of configuration changes that will impact 1187 * this drawable (and thus require completely reloading it). 1188 */ 1189 public abstract int getChangingConfigurations(); 1190 1191 /** 1192 * @hide 1193 */ 1194 public Bitmap getBitmap() { 1195 return null; 1196 } 1197 1198 /** 1199 * Return whether this constant state can have a theme applied. 1200 */ 1201 public boolean canApplyTheme() { 1202 return false; 1203 } 1204 } 1205 1206 /** 1207 * Return a {@link ConstantState} instance that holds the shared state of this Drawable. 1208 * 1209 * @return The ConstantState associated to that Drawable. 1210 * @see ConstantState 1211 * @see Drawable#mutate() 1212 */ 1213 public ConstantState getConstantState() { 1214 return null; 1215 } 1216 1217 private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, 1218 Rect pad, Rect layoutBounds, String srcName) { 1219 1220 if (np != null) { 1221 return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName); 1222 } 1223 1224 return new BitmapDrawable(res, bm); 1225 } 1226 1227 /** 1228 * Ensures the tint filter is consistent with the current tint color and 1229 * mode. 1230 */ 1231 PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint, 1232 PorterDuff.Mode tintMode) { 1233 if (tint == null || tintMode == null) { 1234 return null; 1235 } 1236 1237 final int color = tint.getColorForState(getState(), Color.TRANSPARENT); 1238 if (tintFilter == null) { 1239 return new PorterDuffColorFilter(color, tintMode); 1240 } 1241 1242 tintFilter.setColor(color); 1243 tintFilter.setMode(tintMode); 1244 return tintFilter; 1245 } 1246 1247 /** 1248 * Obtains styled attributes from the theme, if available, or unstyled 1249 * resources if the theme is null. 1250 */ 1251 static TypedArray obtainAttributes( 1252 Resources res, Theme theme, AttributeSet set, int[] attrs) { 1253 if (theme == null) { 1254 return res.obtainAttributes(set, attrs); 1255 } 1256 return theme.obtainStyledAttributes(set, attrs, 0, 0); 1257 } 1258 1259 /** 1260 * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode 1261 * attribute's enum value. 1262 * 1263 * @hide 1264 */ 1265 public static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) { 1266 switch (value) { 1267 case 3: return Mode.SRC_OVER; 1268 case 5: return Mode.SRC_IN; 1269 case 9: return Mode.SRC_ATOP; 1270 case 14: return Mode.MULTIPLY; 1271 case 15: return Mode.SCREEN; 1272 case 16: return Mode.ADD; 1273 default: return defaultMode; 1274 } 1275 } 1276} 1277 1278