RippleDrawable.java revision 6ce6d70f9c78f0197f1369246bf55a5f6b8d7ba4
1/* 2 * Copyright (C) 2013 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.annotation.Nullable; 21import android.content.res.ColorStateList; 22import android.content.res.Resources; 23import android.content.res.Resources.Theme; 24import android.content.res.TypedArray; 25import android.graphics.Canvas; 26import android.graphics.Color; 27import android.graphics.ColorFilter; 28import android.graphics.Outline; 29import android.graphics.Paint; 30import android.graphics.PixelFormat; 31import android.graphics.PorterDuff.Mode; 32import android.graphics.PorterDuffXfermode; 33import android.graphics.Rect; 34import android.util.AttributeSet; 35import android.util.DisplayMetrics; 36import android.util.Log; 37 38import com.android.internal.R; 39 40import org.xmlpull.v1.XmlPullParser; 41import org.xmlpull.v1.XmlPullParserException; 42 43import java.io.IOException; 44 45/** 46 * Drawable that shows a ripple effect in response to state changes. The 47 * anchoring position of the ripple for a given state may be specified by 48 * calling {@link #setHotspot(float, float)} with the corresponding state 49 * attribute identifier. 50 * <p> 51 * A touch feedback drawable may contain multiple child layers, including a 52 * special mask layer that is not drawn to the screen. A single layer may be set 53 * as the mask by specifying its android:id value as {@link android.R.id#mask}. 54 * <pre> 55 * <code><!-- A red ripple masked against an opaque rectangle. --/> 56 * <ripple android:color="#ffff0000"> 57 * <item android:id="@android:id/mask" 58 * android:drawable="@android:color/white" /> 59 * <ripple /></code> 60 * </pre> 61 * <p> 62 * If a mask layer is set, the ripple effect will be masked against that layer 63 * before it is drawn over the composite of the remaining child layers. 64 * <p> 65 * If no mask layer is set, the ripple effect is masked against the composite 66 * of the child layers. 67 * <pre> 68 * <code><!-- A blue ripple drawn atop a black rectangle. --/> 69 * <ripple android:color="#ff00ff00"> 70 * <item android:drawable="@android:color/black" /> 71 * <ripple /> 72 * 73 * <!-- A red ripple drawn atop a drawable resource. --/> 74 * <ripple android:color="#ff00ff00"> 75 * <item android:drawable="@drawable/my_drawable" /> 76 * <ripple /></code> 77 * </pre> 78 * <p> 79 * If no child layers or mask is specified and the ripple is set as a View 80 * background, the ripple will be drawn atop the first available parent 81 * background within the View's hierarchy. In this case, the drawing region 82 * may extend outside of the Drawable bounds. 83 * <pre> 84 * <code><!-- An unbounded green ripple. --/> 85 * <ripple android:color="#ff0000ff" /></code> 86 * </pre> 87 * 88 * @attr ref android.R.styleable#RippleDrawable_color 89 */ 90public class RippleDrawable extends LayerDrawable { 91 private static final String LOG_TAG = RippleDrawable.class.getSimpleName(); 92 private static final PorterDuffXfermode DST_IN = new PorterDuffXfermode(Mode.DST_IN); 93 private static final PorterDuffXfermode SRC_ATOP = new PorterDuffXfermode(Mode.SRC_ATOP); 94 private static final PorterDuffXfermode SRC_OVER = new PorterDuffXfermode(Mode.SRC_OVER); 95 96 /** 97 * Constant for automatically determining the maximum ripple radius. 98 * 99 * @see #setMaxRadius(int) 100 * @hide 101 */ 102 public static final int RADIUS_AUTO = -1; 103 104 /** The maximum number of ripples supported. */ 105 private static final int MAX_RIPPLES = 10; 106 107 private final Rect mTempRect = new Rect(); 108 109 /** Current ripple effect bounds, used to constrain ripple effects. */ 110 private final Rect mHotspotBounds = new Rect(); 111 112 /** Current drawing bounds, used to compute dirty region. */ 113 private final Rect mDrawingBounds = new Rect(); 114 115 /** Current dirty bounds, union of current and previous drawing bounds. */ 116 private final Rect mDirtyBounds = new Rect(); 117 118 private final RippleState mState; 119 120 /** The masking layer, e.g. the layer with id R.id.mask. */ 121 private Drawable mMask; 122 123 /** The current background. May be actively animating or pending entry. */ 124 private RippleBackground mBackground; 125 126 /** Whether we expect to draw a background when visible. */ 127 private boolean mBackgroundActive; 128 129 /** The current ripple. May be actively animating or pending entry. */ 130 private Ripple mRipple; 131 132 /** Whether we expect to draw a ripple when visible. */ 133 private boolean mRippleActive; 134 135 // Hotspot coordinates that are awaiting activation. 136 private float mPendingX; 137 private float mPendingY; 138 private boolean mHasPending; 139 140 /** 141 * Lazily-created array of actively animating ripples. Inactive ripples are 142 * pruned during draw(). The locations of these will not change. 143 */ 144 private Ripple[] mAnimatingRipples; 145 private int mAnimatingRipplesCount = 0; 146 147 /** Paint used to control appearance of ripples. */ 148 private Paint mRipplePaint; 149 150 /** Paint used to control reveal layer masking. */ 151 private Paint mMaskingPaint; 152 153 /** Target density of the display into which ripples are drawn. */ 154 private float mDensity = 1.0f; 155 156 /** Whether bounds are being overridden. */ 157 private boolean mOverrideBounds; 158 159 /** 160 * Constructor used for drawable inflation. 161 */ 162 RippleDrawable() { 163 this(new RippleState(null, null, null), null, null); 164 } 165 166 /** 167 * Creates a new ripple drawable with the specified ripple color and 168 * optional content and mask drawables. 169 * 170 * @param color The ripple color 171 * @param content The content drawable, may be {@code null} 172 * @param mask The mask drawable, may be {@code null} 173 */ 174 public RippleDrawable(@NonNull ColorStateList color, @Nullable Drawable content, 175 @Nullable Drawable mask) { 176 this(new RippleState(null, null, null), null, null); 177 178 if (color == null) { 179 throw new IllegalArgumentException("RippleDrawable requires a non-null color"); 180 } 181 182 if (content != null) { 183 addLayer(content, null, 0, 0, 0, 0, 0); 184 } 185 186 if (mask != null) { 187 addLayer(mask, null, android.R.id.mask, 0, 0, 0, 0); 188 } 189 190 setColor(color); 191 ensurePadding(); 192 initializeFromState(); 193 } 194 195 @Override 196 public void setAlpha(int alpha) { 197 super.setAlpha(alpha); 198 199 // TODO: Should we support this? 200 } 201 202 @Override 203 public void setColorFilter(ColorFilter cf) { 204 super.setColorFilter(cf); 205 206 // TODO: Should we support this? 207 } 208 209 @Override 210 public int getOpacity() { 211 // Worst-case scenario. 212 return PixelFormat.TRANSLUCENT; 213 } 214 215 @Override 216 protected boolean onStateChange(int[] stateSet) { 217 super.onStateChange(stateSet); 218 219 boolean enabled = false; 220 boolean pressed = false; 221 boolean focused = false; 222 223 final int N = stateSet.length; 224 for (int i = 0; i < N; i++) { 225 if (stateSet[i] == R.attr.state_enabled) { 226 enabled = true; 227 } 228 if (stateSet[i] == R.attr.state_focused 229 || stateSet[i] == R.attr.state_selected) { 230 focused = true; 231 } 232 if (stateSet[i] == R.attr.state_pressed) { 233 pressed = true; 234 } 235 } 236 237 setRippleActive(enabled && pressed); 238 setBackgroundActive(focused || (enabled && pressed)); 239 240 // Update the paint color. Only applicable when animated in software. 241 if (mRipplePaint != null && mState.mColor != null) { 242 final ColorStateList stateList = mState.mColor; 243 final int newColor = stateList.getColorForState(stateSet, 0); 244 final int oldColor = mRipplePaint.getColor(); 245 if (oldColor != newColor) { 246 mRipplePaint.setColor(newColor); 247 invalidateSelf(); 248 return true; 249 } 250 } 251 252 return false; 253 } 254 255 private void setRippleActive(boolean active) { 256 if (mRippleActive != active) { 257 mRippleActive = active; 258 if (active) { 259 activateRipple(); 260 } else { 261 removeRipple(); 262 } 263 } 264 } 265 266 private void setBackgroundActive(boolean active) { 267 if (mBackgroundActive != active) { 268 mBackgroundActive = active; 269 if (active) { 270 activateBackground(); 271 } else { 272 removeBackground(); 273 } 274 } 275 } 276 277 @Override 278 protected void onBoundsChange(Rect bounds) { 279 super.onBoundsChange(bounds); 280 281 if (!mOverrideBounds) { 282 mHotspotBounds.set(bounds); 283 onHotspotBoundsChanged(); 284 } 285 286 invalidateSelf(); 287 } 288 289 @Override 290 public boolean setVisible(boolean visible, boolean restart) { 291 final boolean changed = super.setVisible(visible, restart); 292 293 if (!visible) { 294 clearHotspots(); 295 } else if (changed) { 296 // If we just became visible, ensure the background and ripple 297 // visibilities are consistent with their internal states. 298 if (mRippleActive) { 299 activateRipple(); 300 } 301 302 if (mBackgroundActive) { 303 activateBackground(); 304 } 305 } 306 307 return changed; 308 } 309 310 /** 311 * @hide 312 */ 313 @Override 314 public boolean isProjected() { 315 return getNumberOfLayers() == 0; 316 } 317 318 @Override 319 public boolean isStateful() { 320 return true; 321 } 322 323 public void setColor(ColorStateList color) { 324 mState.mColor = color; 325 invalidateSelf(); 326 } 327 328 @Override 329 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 330 throws XmlPullParserException, IOException { 331 final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.RippleDrawable); 332 updateStateFromTypedArray(a); 333 a.recycle(); 334 335 // Force padding default to STACK before inflating. 336 setPaddingMode(PADDING_MODE_STACK); 337 338 super.inflate(r, parser, attrs, theme); 339 340 setTargetDensity(r.getDisplayMetrics()); 341 initializeFromState(); 342 } 343 344 @Override 345 public boolean setDrawableByLayerId(int id, Drawable drawable) { 346 if (super.setDrawableByLayerId(id, drawable)) { 347 if (id == R.id.mask) { 348 mMask = drawable; 349 } 350 351 return true; 352 } 353 354 return false; 355 } 356 357 /** 358 * Specifies how layer padding should affect the bounds of subsequent 359 * layers. The default and recommended value for RippleDrawable is 360 * {@link #PADDING_MODE_STACK}. 361 * 362 * @param mode padding mode, one of: 363 * <ul> 364 * <li>{@link #PADDING_MODE_NEST} to nest each layer inside the 365 * padding of the previous layer 366 * <li>{@link #PADDING_MODE_STACK} to stack each layer directly 367 * atop the previous layer 368 * </ul> 369 * @see #getPaddingMode() 370 */ 371 @Override 372 public void setPaddingMode(int mode) { 373 super.setPaddingMode(mode); 374 } 375 376 /** 377 * Initializes the constant state from the values in the typed array. 378 */ 379 private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException { 380 final RippleState state = mState; 381 382 // Account for any configuration changes. 383 state.mChangingConfigurations |= a.getChangingConfigurations(); 384 385 // Extract the theme attributes, if any. 386 state.mTouchThemeAttrs = a.extractThemeAttrs(); 387 388 final ColorStateList color = a.getColorStateList(R.styleable.RippleDrawable_color); 389 if (color != null) { 390 mState.mColor = color; 391 } 392 393 // If we're not waiting on a theme, verify required attributes. 394 if (state.mTouchThemeAttrs == null && mState.mColor == null) { 395 throw new XmlPullParserException(a.getPositionDescription() + 396 ": <ripple> requires a valid color attribute"); 397 } 398 } 399 400 /** 401 * Set the density at which this drawable will be rendered. 402 * 403 * @param metrics The display metrics for this drawable. 404 */ 405 private void setTargetDensity(DisplayMetrics metrics) { 406 if (mDensity != metrics.density) { 407 mDensity = metrics.density; 408 invalidateSelf(); 409 } 410 } 411 412 @Override 413 public void applyTheme(Theme t) { 414 super.applyTheme(t); 415 416 final RippleState state = mState; 417 if (state == null || state.mTouchThemeAttrs == null) { 418 return; 419 } 420 421 final TypedArray a = t.resolveAttributes(state.mTouchThemeAttrs, 422 R.styleable.RippleDrawable); 423 try { 424 updateStateFromTypedArray(a); 425 } catch (XmlPullParserException e) { 426 throw new RuntimeException(e); 427 } finally { 428 a.recycle(); 429 } 430 431 initializeFromState(); 432 } 433 434 @Override 435 public boolean canApplyTheme() { 436 return super.canApplyTheme() || mState != null && mState.mTouchThemeAttrs != null; 437 } 438 439 @Override 440 public void setHotspot(float x, float y) { 441 if (mRipple == null || mBackground == null) { 442 mPendingX = x; 443 mPendingY = y; 444 mHasPending = true; 445 } 446 447 if (mRipple != null) { 448 mRipple.move(x, y); 449 } 450 451 if (mBackground != null) { 452 mBackground.move(x, y); 453 } 454 } 455 456 /** 457 * Creates an active hotspot at the specified location. 458 */ 459 private void activateBackground() { 460 if (mBackground == null) { 461 final float x; 462 final float y; 463 if (mHasPending) { 464 mHasPending = false; 465 x = mPendingX; 466 y = mPendingY; 467 } else { 468 x = mHotspotBounds.exactCenterX(); 469 y = mHotspotBounds.exactCenterY(); 470 } 471 mBackground = new RippleBackground(this, mHotspotBounds, x, y); 472 } 473 474 final int color = mState.mColor.getColorForState(getState(), Color.TRANSPARENT); 475 mBackground.setup(mState.mMaxRadius, color, mDensity); 476 mBackground.enter(); 477 } 478 479 private void removeBackground() { 480 if (mBackground != null) { 481 // Don't null out the background, we need it to draw! 482 mBackground.exit(); 483 } 484 } 485 486 /** 487 * Creates an active hotspot at the specified location. 488 */ 489 private void activateRipple() { 490 if (mAnimatingRipplesCount >= MAX_RIPPLES) { 491 // This should never happen unless the user is tapping like a maniac 492 // or there is a bug that's preventing ripples from being removed. 493 return; 494 } 495 496 if (mRipple == null) { 497 final float x; 498 final float y; 499 if (mHasPending) { 500 mHasPending = false; 501 x = mPendingX; 502 y = mPendingY; 503 } else { 504 x = mHotspotBounds.exactCenterX(); 505 y = mHotspotBounds.exactCenterY(); 506 } 507 mRipple = new Ripple(this, mHotspotBounds, x, y); 508 } 509 510 final int color = mState.mColor.getColorForState(getState(), Color.TRANSPARENT); 511 mRipple.setup(mState.mMaxRadius, color, mDensity); 512 mRipple.enter(); 513 514 if (mAnimatingRipples == null) { 515 mAnimatingRipples = new Ripple[MAX_RIPPLES]; 516 } 517 mAnimatingRipples[mAnimatingRipplesCount++] = mRipple; 518 } 519 520 private void removeRipple() { 521 if (mRipple != null) { 522 mRipple.exit(); 523 mRipple = null; 524 } 525 } 526 527 private void clearHotspots() { 528 if (mRipple != null) { 529 mRipple.cancel(); 530 mRipple = null; 531 } 532 533 if (mBackground != null) { 534 mBackground.cancel(); 535 mBackground = null; 536 } 537 538 final int count = mAnimatingRipplesCount; 539 final Ripple[] ripples = mAnimatingRipples; 540 for (int i = 0; i < count; i++) { 541 // Calling cancel may remove the ripple from the animating ripple 542 // array, so cache the reference before nulling it out. 543 final Ripple ripple = ripples[i]; 544 ripples[i] = null; 545 ripple.cancel(); 546 } 547 548 mAnimatingRipplesCount = 0; 549 invalidateSelf(); 550 } 551 552 @Override 553 public void setHotspotBounds(int left, int top, int right, int bottom) { 554 mOverrideBounds = true; 555 mHotspotBounds.set(left, top, right, bottom); 556 557 onHotspotBoundsChanged(); 558 } 559 560 /** @hide */ 561 @Override 562 public void getHotspotBounds(Rect outRect) { 563 outRect.set(mHotspotBounds); 564 } 565 566 /** 567 * Notifies all the animating ripples that the hotspot bounds have changed. 568 */ 569 private void onHotspotBoundsChanged() { 570 final int count = mAnimatingRipplesCount; 571 final Ripple[] ripples = mAnimatingRipples; 572 for (int i = 0; i < count; i++) { 573 ripples[i].onHotspotBoundsChanged(); 574 } 575 576 if (mBackground != null) { 577 mBackground.onHotspotBoundsChanged(); 578 } 579 } 580 581 /** 582 * Populates <code>outline</code> with the first available layer outline, 583 * excluding the mask layer. Returns <code>true</code> if an outline is 584 * available, <code>false</code> otherwise. 585 * 586 * @param outline Outline in which to place the first available layer outline 587 * @return <code>true</code> if an outline is available 588 */ 589 @Override 590 public void getOutline(@NonNull Outline outline) { 591 final LayerState state = mLayerState; 592 final ChildDrawable[] children = state.mChildren; 593 final int N = state.mNum; 594 for (int i = 0; i < N; i++) { 595 if (children[i].mId != R.id.mask) { 596 children[i].mDrawable.getOutline(outline); 597 if (!outline.isEmpty()) return; 598 } 599 } 600 } 601 602 @Override 603 public void draw(@NonNull Canvas canvas) { 604 final boolean isProjected = isProjected(); 605 final boolean hasMask = mMask != null; 606 final boolean drawNonMaskContent = mLayerState.mNum > (hasMask ? 1 : 0); 607 final boolean drawMask = hasMask && mMask.getOpacity() != PixelFormat.OPAQUE; 608 final Rect bounds = isProjected ? getDirtyBounds() : getBounds(); 609 610 // If we have content, draw it into a layer first. 611 final int contentLayer = drawNonMaskContent ? 612 drawContentLayer(canvas, bounds, SRC_OVER) : -1; 613 614 // Next, try to draw the ripples (into a layer if necessary). If we need 615 // to mask against the underlying content, set the xfermode to SRC_ATOP. 616 final PorterDuffXfermode xfermode = (hasMask || !drawNonMaskContent) ? SRC_OVER : SRC_ATOP; 617 618 // If we have a background and a non-opaque mask, draw the masking layer. 619 final int backgroundLayer = drawBackgroundLayer(canvas, bounds, xfermode); 620 if (backgroundLayer >= 0) { 621 if (drawMask) { 622 drawMaskingLayer(canvas, bounds, DST_IN); 623 } 624 canvas.restoreToCount(backgroundLayer); 625 } 626 627 // If we have ripples and a non-opaque mask, draw the masking layer. 628 final int rippleLayer = drawRippleLayer(canvas, bounds, xfermode); 629 if (rippleLayer >= 0) { 630 if (drawMask) { 631 drawMaskingLayer(canvas, bounds, DST_IN); 632 } 633 canvas.restoreToCount(rippleLayer); 634 } 635 636 // Composite the layers if needed. 637 if (contentLayer >= 0) { 638 canvas.restoreToCount(contentLayer); 639 } 640 } 641 642 /** 643 * Removes a ripple from the animating ripple list. 644 * 645 * @param ripple the ripple to remove 646 */ 647 void removeRipple(Ripple ripple) { 648 // Ripple ripple ripple ripple. Ripple ripple. 649 final Ripple[] ripples = mAnimatingRipples; 650 final int count = mAnimatingRipplesCount; 651 final int index = getRippleIndex(ripple); 652 if (index >= 0) { 653 System.arraycopy(ripples, index + 1, ripples, index + 1 - 1, count - (index + 1)); 654 ripples[count - 1] = null; 655 mAnimatingRipplesCount--; 656 invalidateSelf(); 657 } 658 } 659 660 void removeBackground(RippleBackground background) { 661 if (mBackground == background) { 662 mBackground = null; 663 invalidateSelf(); 664 } 665 } 666 667 private int getRippleIndex(Ripple ripple) { 668 final Ripple[] ripples = mAnimatingRipples; 669 final int count = mAnimatingRipplesCount; 670 for (int i = 0; i < count; i++) { 671 if (ripples[i] == ripple) { 672 return i; 673 } 674 } 675 return -1; 676 } 677 678 private int drawContentLayer(Canvas canvas, Rect bounds, PorterDuffXfermode mode) { 679 final ChildDrawable[] array = mLayerState.mChildren; 680 final int count = mLayerState.mNum; 681 682 // We don't need a layer if we don't expect to draw any ripples, we have 683 // an explicit mask, or if the non-mask content is all opaque. 684 boolean needsLayer = false; 685 if ((mAnimatingRipplesCount > 0 || mBackground != null) && mMask == null) { 686 for (int i = 0; i < count; i++) { 687 if (array[i].mId != R.id.mask 688 && array[i].mDrawable.getOpacity() != PixelFormat.OPAQUE) { 689 needsLayer = true; 690 break; 691 } 692 } 693 } 694 695 final Paint maskingPaint = getMaskingPaint(mode); 696 final int restoreToCount = needsLayer ? canvas.saveLayer(bounds.left, bounds.top, 697 bounds.right, bounds.bottom, maskingPaint) : -1; 698 699 // Draw everything except the mask. 700 for (int i = 0; i < count; i++) { 701 if (array[i].mId != R.id.mask) { 702 array[i].mDrawable.draw(canvas); 703 } 704 } 705 706 return restoreToCount; 707 } 708 709 private int drawBackgroundLayer(Canvas canvas, Rect bounds, PorterDuffXfermode mode) { 710 // Separate the ripple color and alpha channel. The alpha will be 711 // applied when we merge the ripples down to the canvas. 712 final int rippleARGB; 713 if (mState.mColor != null) { 714 rippleARGB = mState.mColor.getColorForState(getState(), Color.TRANSPARENT); 715 } else { 716 rippleARGB = Color.TRANSPARENT; 717 } 718 719 if (mRipplePaint == null) { 720 mRipplePaint = new Paint(); 721 mRipplePaint.setAntiAlias(true); 722 } 723 724 final int rippleAlpha = Color.alpha(rippleARGB); 725 final Paint ripplePaint = mRipplePaint; 726 ripplePaint.setColor(rippleARGB); 727 ripplePaint.setAlpha(0xFF); 728 729 boolean drewRipples = false; 730 int restoreToCount = -1; 731 int restoreTranslate = -1; 732 733 // Draw background. 734 final RippleBackground background = mBackground; 735 if (background != null) { 736 // If we're masking the ripple layer, make sure we have a layer 737 // first. This will merge SRC_OVER (directly) onto the canvas. 738 final Paint maskingPaint = getMaskingPaint(mode); 739 maskingPaint.setAlpha(rippleAlpha); 740 restoreToCount = canvas.saveLayer(bounds.left, bounds.top, 741 bounds.right, bounds.bottom, maskingPaint); 742 743 restoreTranslate = canvas.save(); 744 // Translate the canvas to the current hotspot bounds. 745 canvas.translate(mHotspotBounds.exactCenterX(), mHotspotBounds.exactCenterY()); 746 747 drewRipples = background.draw(canvas, ripplePaint); 748 } 749 750 // Always restore the translation. 751 if (restoreTranslate >= 0) { 752 canvas.restoreToCount(restoreTranslate); 753 } 754 755 // If we created a layer with no content, merge it immediately. 756 if (restoreToCount >= 0 && !drewRipples) { 757 canvas.restoreToCount(restoreToCount); 758 restoreToCount = -1; 759 } 760 761 return restoreToCount; 762 } 763 764 private int drawRippleLayer(Canvas canvas, Rect bounds, PorterDuffXfermode mode) { 765 // Separate the ripple color and alpha channel. The alpha will be 766 // applied when we merge the ripples down to the canvas. 767 final int rippleARGB; 768 if (mState.mColor != null) { 769 rippleARGB = mState.mColor.getColorForState(getState(), Color.TRANSPARENT); 770 } else { 771 rippleARGB = Color.TRANSPARENT; 772 } 773 774 if (mRipplePaint == null) { 775 mRipplePaint = new Paint(); 776 mRipplePaint.setAntiAlias(true); 777 } 778 779 final int rippleAlpha = Color.alpha(rippleARGB); 780 final Paint ripplePaint = mRipplePaint; 781 ripplePaint.setColor(rippleARGB); 782 ripplePaint.setAlpha(0xFF); 783 784 boolean drewRipples = false; 785 int restoreToCount = -1; 786 int restoreTranslate = -1; 787 788 // Draw ripples and update the animating ripples array. 789 final int count = mAnimatingRipplesCount; 790 final Ripple[] ripples = mAnimatingRipples; 791 for (int i = 0; i < count; i++) { 792 final Ripple ripple = ripples[i]; 793 794 // If we're masking the ripple layer, make sure we have a layer 795 // first. This will merge SRC_OVER (directly) onto the canvas. 796 if (restoreToCount < 0) { 797 final Paint maskingPaint = getMaskingPaint(mode); 798 maskingPaint.setAlpha(rippleAlpha); 799 restoreToCount = canvas.saveLayer(bounds.left, bounds.top, 800 bounds.right, bounds.bottom, maskingPaint); 801 802 restoreTranslate = canvas.save(); 803 // Translate the canvas to the current hotspot bounds. 804 canvas.translate(mHotspotBounds.exactCenterX(), mHotspotBounds.exactCenterY()); 805 } 806 807 drewRipples |= ripple.draw(canvas, ripplePaint); 808 } 809 810 // Always restore the translation. 811 if (restoreTranslate >= 0) { 812 canvas.restoreToCount(restoreTranslate); 813 } 814 815 // If we created a layer with no content, merge it immediately. 816 if (restoreToCount >= 0 && !drewRipples) { 817 canvas.restoreToCount(restoreToCount); 818 restoreToCount = -1; 819 } 820 821 return restoreToCount; 822 } 823 824 private int drawMaskingLayer(Canvas canvas, Rect bounds, PorterDuffXfermode mode) { 825 final int restoreToCount = canvas.saveLayer(bounds.left, bounds.top, 826 bounds.right, bounds.bottom, getMaskingPaint(mode)); 827 828 // Ensure that DST_IN blends using the entire layer. 829 canvas.drawColor(Color.TRANSPARENT); 830 831 mMask.draw(canvas); 832 833 return restoreToCount; 834 } 835 836 private Paint getMaskingPaint(PorterDuffXfermode xfermode) { 837 if (mMaskingPaint == null) { 838 mMaskingPaint = new Paint(); 839 } 840 mMaskingPaint.setXfermode(xfermode); 841 mMaskingPaint.setAlpha(0xFF); 842 return mMaskingPaint; 843 } 844 845 @Override 846 public Rect getDirtyBounds() { 847 if (isProjected()) { 848 final Rect drawingBounds = mDrawingBounds; 849 final Rect dirtyBounds = mDirtyBounds; 850 dirtyBounds.set(drawingBounds); 851 drawingBounds.setEmpty(); 852 853 final int cX = (int) mHotspotBounds.exactCenterX(); 854 final int cY = (int) mHotspotBounds.exactCenterY(); 855 final Rect rippleBounds = mTempRect; 856 final Ripple[] activeRipples = mAnimatingRipples; 857 final int N = mAnimatingRipplesCount; 858 for (int i = 0; i < N; i++) { 859 activeRipples[i].getBounds(rippleBounds); 860 rippleBounds.offset(cX, cY); 861 drawingBounds.union(rippleBounds); 862 } 863 864 final RippleBackground background = mBackground; 865 if (background != null) { 866 background.getBounds(rippleBounds); 867 rippleBounds.offset(cX, cY); 868 drawingBounds.union(rippleBounds); 869 } 870 871 dirtyBounds.union(drawingBounds); 872 dirtyBounds.union(super.getDirtyBounds()); 873 return dirtyBounds; 874 } else { 875 return getBounds(); 876 } 877 } 878 879 @Override 880 public ConstantState getConstantState() { 881 return mState; 882 } 883 884 static class RippleState extends LayerState { 885 int[] mTouchThemeAttrs; 886 ColorStateList mColor = null; 887 int mMaxRadius = RADIUS_AUTO; 888 889 public RippleState(RippleState orig, RippleDrawable owner, Resources res) { 890 super(orig, owner, res); 891 892 if (orig != null) { 893 mTouchThemeAttrs = orig.mTouchThemeAttrs; 894 mColor = orig.mColor; 895 mMaxRadius = orig.mMaxRadius; 896 } 897 } 898 899 @Override 900 public boolean canApplyTheme() { 901 return mTouchThemeAttrs != null || super.canApplyTheme(); 902 } 903 904 @Override 905 public Drawable newDrawable() { 906 return new RippleDrawable(this, null, null); 907 } 908 909 @Override 910 public Drawable newDrawable(Resources res) { 911 return new RippleDrawable(this, res, null); 912 } 913 914 @Override 915 public Drawable newDrawable(Resources res, Theme theme) { 916 return new RippleDrawable(this, res, theme); 917 } 918 } 919 920 /** 921 * Sets the maximum ripple radius in pixels. The default value of 922 * {@link #RADIUS_AUTO} defines the radius as the distance from the center 923 * of the drawable bounds (or hotspot bounds, if specified) to a corner. 924 * 925 * @param maxRadius the maximum ripple radius in pixels or 926 * {@link #RADIUS_AUTO} to automatically determine the maximum 927 * radius based on the bounds 928 * @see #getMaxRadius() 929 * @see #setHotspotBounds(int, int, int, int) 930 * @hide 931 */ 932 public void setMaxRadius(int maxRadius) { 933 if (maxRadius != RADIUS_AUTO && maxRadius < 0) { 934 throw new IllegalArgumentException("maxRadius must be RADIUS_AUTO or >= 0"); 935 } 936 937 mState.mMaxRadius = maxRadius; 938 } 939 940 /** 941 * @return the maximum ripple radius in pixels, or {@link #RADIUS_AUTO} if 942 * the radius is determined automatically 943 * @see #setMaxRadius(int) 944 * @hide 945 */ 946 public int getMaxRadius() { 947 return mState.mMaxRadius; 948 } 949 950 private RippleDrawable(RippleState state, Resources res, Theme theme) { 951 boolean needsTheme = false; 952 953 final RippleState ns; 954 if (theme != null && state != null && state.canApplyTheme()) { 955 ns = new RippleState(state, this, res); 956 needsTheme = true; 957 } else if (state == null) { 958 ns = new RippleState(null, this, res); 959 } else { 960 // We always need a new state since child drawables contain local 961 // state but live within the parent's constant state. 962 // TODO: Move child drawables into local state. 963 ns = new RippleState(state, this, res); 964 } 965 966 if (res != null) { 967 mDensity = res.getDisplayMetrics().density; 968 } 969 970 mState = ns; 971 mLayerState = ns; 972 973 if (ns.mNum > 0) { 974 ensurePadding(); 975 } 976 977 if (needsTheme) { 978 applyTheme(theme); 979 } 980 981 initializeFromState(); 982 } 983 984 private void initializeFromState() { 985 // Initialize from constant state. 986 mMask = findDrawableByLayerId(R.id.mask); 987 } 988} 989