NinePatchDrawable.java revision 47cd8e921db73e894f94ec4729ade90da50996f5
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.ColorFilter; 28import android.graphics.Insets; 29import android.graphics.NinePatch; 30import android.graphics.Outline; 31import android.graphics.Paint; 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.util.AttributeSet; 39import android.util.DisplayMetrics; 40import android.util.LayoutDirection; 41import android.util.TypedValue; 42 43import com.android.internal.R; 44 45import org.xmlpull.v1.XmlPullParser; 46import org.xmlpull.v1.XmlPullParserException; 47 48import java.io.IOException; 49import java.io.InputStream; 50 51/** 52 * 53 * A resizeable bitmap, with stretchable areas that you define. This type of image 54 * is defined in a .png file with a special format. 55 * 56 * <div class="special reference"> 57 * <h3>Developer Guides</h3> 58 * <p>For more information about how to use a NinePatchDrawable, read the 59 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch"> 60 * Canvas and Drawables</a> developer guide. For information about creating a NinePatch image 61 * file using the draw9patch tool, see the 62 * <a href="{@docRoot}guide/developing/tools/draw9patch.html">Draw 9-patch</a> tool guide.</p></div> 63 */ 64public class NinePatchDrawable extends Drawable { 65 // dithering helps a lot, and is pretty cheap, so default is true 66 private static final boolean DEFAULT_DITHER = false; 67 private NinePatchState mNinePatchState; 68 private NinePatch mNinePatch; 69 private PorterDuffColorFilter mTintFilter; 70 private Rect mPadding; 71 private Insets mOpticalInsets = Insets.NONE; 72 private Paint mPaint; 73 private boolean mMutated; 74 75 private int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; 76 77 // These are scaled to match the target density. 78 private int mBitmapWidth = -1; 79 private int mBitmapHeight = -1; 80 81 NinePatchDrawable() { 82 mNinePatchState = new NinePatchState(); 83 } 84 85 /** 86 * Create drawable from raw nine-patch data, not dealing with density. 87 * @deprecated Use {@link #NinePatchDrawable(Resources, Bitmap, byte[], Rect, String)} 88 * to ensure that the drawable has correctly set its target density. 89 */ 90 @Deprecated 91 public NinePatchDrawable(Bitmap bitmap, byte[] chunk, Rect padding, String srcName) { 92 this(new NinePatchState(new NinePatch(bitmap, chunk, srcName), padding), null, null); 93 } 94 95 /** 96 * Create drawable from raw nine-patch data, setting initial target density 97 * based on the display metrics of the resources. 98 */ 99 public NinePatchDrawable(Resources res, Bitmap bitmap, byte[] chunk, 100 Rect padding, String srcName) { 101 this(new NinePatchState(new NinePatch(bitmap, chunk, srcName), padding), res, null); 102 mNinePatchState.mTargetDensity = mTargetDensity; 103 } 104 105 /** 106 * Create drawable from raw nine-patch data, setting initial target density 107 * based on the display metrics of the resources. 108 * 109 * @hide 110 */ 111 public NinePatchDrawable(Resources res, Bitmap bitmap, byte[] chunk, 112 Rect padding, Rect opticalInsets, String srcName) { 113 this(new NinePatchState(new NinePatch(bitmap, chunk, srcName), padding, opticalInsets), 114 res, null); 115 mNinePatchState.mTargetDensity = mTargetDensity; 116 } 117 118 /** 119 * Create drawable from existing nine-patch, not dealing with density. 120 * @deprecated Use {@link #NinePatchDrawable(Resources, NinePatch)} 121 * to ensure that the drawable has correctly set its target density. 122 */ 123 @Deprecated 124 public NinePatchDrawable(NinePatch patch) { 125 this(new NinePatchState(patch, new Rect()), null, null); 126 } 127 128 /** 129 * Create drawable from existing nine-patch, setting initial target density 130 * based on the display metrics of the resources. 131 */ 132 public NinePatchDrawable(Resources res, NinePatch patch) { 133 this(new NinePatchState(patch, new Rect()), res, null); 134 mNinePatchState.mTargetDensity = mTargetDensity; 135 } 136 137 /** 138 * Set the density scale at which this drawable will be rendered. This 139 * method assumes the drawable will be rendered at the same density as the 140 * specified canvas. 141 * 142 * @param canvas The Canvas from which the density scale must be obtained. 143 * 144 * @see android.graphics.Bitmap#setDensity(int) 145 * @see android.graphics.Bitmap#getDensity() 146 */ 147 public void setTargetDensity(Canvas canvas) { 148 setTargetDensity(canvas.getDensity()); 149 } 150 151 /** 152 * Set the density scale at which this drawable will be rendered. 153 * 154 * @param metrics The DisplayMetrics indicating the density scale for this drawable. 155 * 156 * @see android.graphics.Bitmap#setDensity(int) 157 * @see android.graphics.Bitmap#getDensity() 158 */ 159 public void setTargetDensity(DisplayMetrics metrics) { 160 setTargetDensity(metrics.densityDpi); 161 } 162 163 /** 164 * Set the density at which this drawable will be rendered. 165 * 166 * @param density The density scale for this drawable. 167 * 168 * @see android.graphics.Bitmap#setDensity(int) 169 * @see android.graphics.Bitmap#getDensity() 170 */ 171 public void setTargetDensity(int density) { 172 if (density != mTargetDensity) { 173 mTargetDensity = density == 0 ? DisplayMetrics.DENSITY_DEFAULT : density; 174 if (mNinePatch != null) { 175 computeBitmapSize(); 176 } 177 invalidateSelf(); 178 } 179 } 180 181 private static Insets scaleFromDensity(Insets insets, int sdensity, int tdensity) { 182 int left = Bitmap.scaleFromDensity(insets.left, sdensity, tdensity); 183 int top = Bitmap.scaleFromDensity(insets.top, sdensity, tdensity); 184 int right = Bitmap.scaleFromDensity(insets.right, sdensity, tdensity); 185 int bottom = Bitmap.scaleFromDensity(insets.bottom, sdensity, tdensity); 186 return Insets.of(left, top, right, bottom); 187 } 188 189 private void computeBitmapSize() { 190 final int sdensity = mNinePatch.getDensity(); 191 final int tdensity = mTargetDensity; 192 if (sdensity == tdensity) { 193 mBitmapWidth = mNinePatch.getWidth(); 194 mBitmapHeight = mNinePatch.getHeight(); 195 mOpticalInsets = mNinePatchState.mOpticalInsets; 196 } else { 197 mBitmapWidth = Bitmap.scaleFromDensity(mNinePatch.getWidth(), sdensity, tdensity); 198 mBitmapHeight = Bitmap.scaleFromDensity(mNinePatch.getHeight(), sdensity, tdensity); 199 if (mNinePatchState.mPadding != null && mPadding != null) { 200 Rect dest = mPadding; 201 Rect src = mNinePatchState.mPadding; 202 if (dest == src) { 203 mPadding = dest = new Rect(src); 204 } 205 dest.left = Bitmap.scaleFromDensity(src.left, sdensity, tdensity); 206 dest.top = Bitmap.scaleFromDensity(src.top, sdensity, tdensity); 207 dest.right = Bitmap.scaleFromDensity(src.right, sdensity, tdensity); 208 dest.bottom = Bitmap.scaleFromDensity(src.bottom, sdensity, tdensity); 209 } 210 mOpticalInsets = scaleFromDensity(mNinePatchState.mOpticalInsets, sdensity, tdensity); 211 } 212 } 213 214 private void setNinePatch(NinePatch ninePatch) { 215 if (mNinePatch != ninePatch) { 216 mNinePatch = ninePatch; 217 if (ninePatch != null) { 218 computeBitmapSize(); 219 } else { 220 mBitmapWidth = mBitmapHeight = -1; 221 mOpticalInsets = Insets.NONE; 222 } 223 invalidateSelf(); 224 } 225 } 226 227 @Override 228 public void draw(Canvas canvas) { 229 final Rect bounds = getBounds(); 230 231 final boolean clearColorFilter; 232 if (mTintFilter != null && getPaint().getColorFilter() == null) { 233 mPaint.setColorFilter(mTintFilter); 234 clearColorFilter = true; 235 } else { 236 clearColorFilter = false; 237 } 238 239 final boolean needsMirroring = needsMirroring(); 240 if (needsMirroring) { 241 // Mirror the 9patch 242 canvas.translate(bounds.right - bounds.left, 0); 243 canvas.scale(-1.0f, 1.0f); 244 } 245 246 final int restoreAlpha; 247 if (mNinePatchState.mBaseAlpha != 1.0f) { 248 final Paint p = getPaint(); 249 restoreAlpha = p.getAlpha(); 250 p.setAlpha((int) (restoreAlpha * mNinePatchState.mBaseAlpha + 0.5f)); 251 } else { 252 restoreAlpha = -1; 253 } 254 255 mNinePatch.draw(canvas, bounds, mPaint); 256 257 if (clearColorFilter) { 258 mPaint.setColorFilter(null); 259 } 260 261 if (restoreAlpha >= 0) { 262 mPaint.setAlpha(restoreAlpha); 263 } 264 } 265 266 @Override 267 public int getChangingConfigurations() { 268 return super.getChangingConfigurations() | mNinePatchState.mChangingConfigurations; 269 } 270 271 @Override 272 public boolean getPadding(Rect padding) { 273 final Rect scaledPadding = mPadding; 274 if (scaledPadding != null) { 275 if (needsMirroring()) { 276 padding.set(scaledPadding.right, scaledPadding.top, 277 scaledPadding.left, scaledPadding.bottom); 278 } else { 279 padding.set(scaledPadding); 280 } 281 return (padding.left | padding.top | padding.right | padding.bottom) != 0; 282 } 283 return false; 284 } 285 286 @Override 287 public boolean getOutline(@NonNull Outline outline) { 288 final Rect bounds = getBounds(); 289 if (bounds.isEmpty()) return false; 290 291 if (mNinePatchState != null) { 292 NinePatch.InsetStruct insets = mNinePatchState.getBitmap().getNinePatchInsets(); 293 if (insets != null) { 294 final Rect outlineInsets = insets.outlineRect; 295 outline.setRoundRect(bounds.left + outlineInsets.left, 296 bounds.top + outlineInsets.top, 297 bounds.right - outlineInsets.right, 298 bounds.bottom - outlineInsets.bottom, 299 insets.outlineRadius); 300 outline.setFilled(insets.outlineFilled); 301 return true; 302 } 303 } 304 return super.getOutline(outline); 305 } 306 307 /** 308 * @hide 309 */ 310 @Override 311 public Insets getOpticalInsets() { 312 if (needsMirroring()) { 313 return Insets.of(mOpticalInsets.right, mOpticalInsets.top, 314 mOpticalInsets.left, mOpticalInsets.bottom); 315 } else { 316 return mOpticalInsets; 317 } 318 } 319 320 @Override 321 public void setAlpha(int alpha) { 322 if (mPaint == null && alpha == 0xFF) { 323 // Fast common case -- leave at normal alpha. 324 return; 325 } 326 getPaint().setAlpha(alpha); 327 invalidateSelf(); 328 } 329 330 @Override 331 public int getAlpha() { 332 if (mPaint == null) { 333 // Fast common case -- normal alpha. 334 return 0xFF; 335 } 336 return getPaint().getAlpha(); 337 } 338 339 @Override 340 public void setColorFilter(ColorFilter cf) { 341 if (mPaint == null && cf == null) { 342 // Fast common case -- leave at no color filter. 343 return; 344 } 345 getPaint().setColorFilter(cf); 346 invalidateSelf(); 347 } 348 349 @Override 350 public void setTint(ColorStateList tint, PorterDuff.Mode tintMode) { 351 final NinePatchState state = mNinePatchState; 352 state.mTint = tint; 353 state.mTintMode = tintMode; 354 355 mTintFilter = updateTintFilter(mTintFilter, tint, tintMode); 356 invalidateSelf(); 357 } 358 359 @Override 360 public void setDither(boolean dither) { 361 //noinspection PointlessBooleanExpression 362 if (mPaint == null && dither == DEFAULT_DITHER) { 363 // Fast common case -- leave at default dither. 364 return; 365 } 366 367 getPaint().setDither(dither); 368 invalidateSelf(); 369 } 370 371 @Override 372 public void setAutoMirrored(boolean mirrored) { 373 mNinePatchState.mAutoMirrored = mirrored; 374 } 375 376 private boolean needsMirroring() { 377 return isAutoMirrored() && getLayoutDirection() == LayoutDirection.RTL; 378 } 379 380 @Override 381 public boolean isAutoMirrored() { 382 return mNinePatchState.mAutoMirrored; 383 } 384 385 @Override 386 public void setFilterBitmap(boolean filter) { 387 getPaint().setFilterBitmap(filter); 388 invalidateSelf(); 389 } 390 391 @Override 392 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 393 throws XmlPullParserException, IOException { 394 super.inflate(r, parser, attrs, theme); 395 396 final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.NinePatchDrawable); 397 updateStateFromTypedArray(a); 398 a.recycle(); 399 } 400 401 /** 402 * Updates the constant state from the values in the typed array. 403 */ 404 private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException { 405 final Resources r = a.getResources(); 406 final NinePatchState state = mNinePatchState; 407 408 // Account for any configuration changes. 409 state.mChangingConfigurations |= a.getChangingConfigurations(); 410 411 // Extract the theme attributes, if any. 412 state.mThemeAttrs = a.extractThemeAttrs(); 413 414 state.mDither = a.getBoolean(R.styleable.NinePatchDrawable_dither, state.mDither); 415 416 final int srcResId = a.getResourceId(R.styleable.NinePatchDrawable_src, 0); 417 if (srcResId != 0) { 418 final BitmapFactory.Options options = new BitmapFactory.Options(); 419 options.inDither = !state.mDither; 420 options.inScreenDensity = r.getDisplayMetrics().noncompatDensityDpi; 421 422 final Rect padding = new Rect(); 423 final Rect opticalInsets = new Rect(); 424 Bitmap bitmap = null; 425 426 try { 427 final TypedValue value = new TypedValue(); 428 final InputStream is = r.openRawResource(srcResId, value); 429 430 bitmap = BitmapFactory.decodeResourceStream(r, value, is, padding, options); 431 432 is.close(); 433 } catch (IOException e) { 434 // Ignore 435 } 436 437 if (bitmap == null) { 438 throw new XmlPullParserException(a.getPositionDescription() + 439 ": <nine-patch> requires a valid src attribute"); 440 } else if (bitmap.getNinePatchChunk() == null) { 441 throw new XmlPullParserException(a.getPositionDescription() + 442 ": <nine-patch> requires a valid 9-patch source image"); 443 } 444 445 // Hey, now might be a good time to actually load optical bounds! 446 bitmap.getOpticalInsets(opticalInsets); 447 448 state.mNinePatch = new NinePatch(bitmap, bitmap.getNinePatchChunk()); 449 state.mPadding = padding; 450 state.mOpticalInsets = Insets.of(opticalInsets); 451 } 452 453 state.mAutoMirrored = a.getBoolean( 454 R.styleable.NinePatchDrawable_autoMirrored, state.mAutoMirrored); 455 state.mBaseAlpha = a.getFloat(R.styleable.NinePatchDrawable_alpha, state.mBaseAlpha); 456 457 final int tintMode = a.getInt(R.styleable.NinePatchDrawable_tintMode, -1); 458 if (tintMode != -1) { 459 state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN); 460 } 461 462 final ColorStateList tint = a.getColorStateList(R.styleable.NinePatchDrawable_tint); 463 if (tint != null) { 464 state.mTint = tint; 465 } 466 467 // Update local properties. 468 initializeWithState(state, r); 469 470 // Push density applied by setNinePatchState into state. 471 state.mTargetDensity = mTargetDensity; 472 } 473 474 @Override 475 public void applyTheme(Theme t) { 476 super.applyTheme(t); 477 478 final NinePatchState state = mNinePatchState; 479 if (state == null || state.mThemeAttrs == null) { 480 return; 481 } 482 483 final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.NinePatchDrawable); 484 try { 485 updateStateFromTypedArray(a); 486 } catch (XmlPullParserException e) { 487 throw new RuntimeException(e); 488 } finally { 489 a.recycle(); 490 } 491 } 492 493 @Override 494 public boolean canApplyTheme() { 495 return mNinePatchState != null && mNinePatchState.mThemeAttrs != null; 496 } 497 498 public Paint getPaint() { 499 if (mPaint == null) { 500 mPaint = new Paint(); 501 mPaint.setDither(DEFAULT_DITHER); 502 } 503 return mPaint; 504 } 505 506 /** 507 * Retrieves the width of the source .png file (before resizing). 508 */ 509 @Override 510 public int getIntrinsicWidth() { 511 return mBitmapWidth; 512 } 513 514 /** 515 * Retrieves the height of the source .png file (before resizing). 516 */ 517 @Override 518 public int getIntrinsicHeight() { 519 return mBitmapHeight; 520 } 521 522 @Override 523 public int getMinimumWidth() { 524 return mBitmapWidth; 525 } 526 527 @Override 528 public int getMinimumHeight() { 529 return mBitmapHeight; 530 } 531 532 /** 533 * Returns a {@link android.graphics.PixelFormat graphics.PixelFormat} 534 * value of OPAQUE or TRANSLUCENT. 535 */ 536 @Override 537 public int getOpacity() { 538 return mNinePatch.hasAlpha() || (mPaint != null && mPaint.getAlpha() < 255) ? 539 PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; 540 } 541 542 @Override 543 public Region getTransparentRegion() { 544 return mNinePatch.getTransparentRegion(getBounds()); 545 } 546 547 @Override 548 public ConstantState getConstantState() { 549 mNinePatchState.mChangingConfigurations = getChangingConfigurations(); 550 return mNinePatchState; 551 } 552 553 @Override 554 public Drawable mutate() { 555 if (!mMutated && super.mutate() == this) { 556 mNinePatchState = new NinePatchState(mNinePatchState); 557 mNinePatch = mNinePatchState.mNinePatch; 558 mMutated = true; 559 } 560 return this; 561 } 562 563 @Override 564 protected boolean onStateChange(int[] stateSet) { 565 final NinePatchState state = mNinePatchState; 566 if (state.mTint != null && state.mTintMode != null) { 567 mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode); 568 return true; 569 } 570 571 return false; 572 } 573 574 @Override 575 public boolean isStateful() { 576 final NinePatchState s = mNinePatchState; 577 return super.isStateful() || (s.mTint != null && s.mTint.isStateful()); 578 } 579 580 final static class NinePatchState extends ConstantState { 581 // Values loaded during inflation. 582 int[] mThemeAttrs = null; 583 NinePatch mNinePatch = null; 584 ColorStateList mTint = null; 585 Mode mTintMode = Mode.SRC_IN; 586 Rect mPadding = null; 587 Insets mOpticalInsets = Insets.NONE; 588 float mBaseAlpha = 1.0f; 589 boolean mDither = DEFAULT_DITHER; 590 int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; 591 boolean mAutoMirrored = false; 592 593 int mChangingConfigurations; 594 595 NinePatchState() { 596 // Empty constructor. 597 } 598 599 NinePatchState(NinePatch ninePatch, Rect padding) { 600 this(ninePatch, padding, null, DEFAULT_DITHER, false); 601 } 602 603 NinePatchState(NinePatch ninePatch, Rect padding, Rect opticalInsets) { 604 this(ninePatch, padding, opticalInsets, DEFAULT_DITHER, false); 605 } 606 607 NinePatchState(NinePatch ninePatch, Rect rect, Rect opticalInsets, boolean dither, 608 boolean autoMirror) { 609 mNinePatch = ninePatch; 610 mPadding = rect; 611 mOpticalInsets = Insets.of(opticalInsets); 612 mDither = dither; 613 mAutoMirrored = autoMirror; 614 } 615 616 // Copy constructor 617 618 NinePatchState(NinePatchState state) { 619 // We don't deep-copy any fields because they are all immutable. 620 mNinePatch = state.mNinePatch; 621 mTint = state.mTint; 622 mTintMode = state.mTintMode; 623 mThemeAttrs = state.mThemeAttrs; 624 mPadding = state.mPadding; 625 mOpticalInsets = state.mOpticalInsets; 626 mBaseAlpha = state.mBaseAlpha; 627 mDither = state.mDither; 628 mChangingConfigurations = state.mChangingConfigurations; 629 mTargetDensity = state.mTargetDensity; 630 mAutoMirrored = state.mAutoMirrored; 631 } 632 633 @Override 634 public boolean canApplyTheme() { 635 return mThemeAttrs != null; 636 } 637 638 @Override 639 public Bitmap getBitmap() { 640 return mNinePatch.getBitmap(); 641 } 642 643 @Override 644 public Drawable newDrawable() { 645 return new NinePatchDrawable(this, null, null); 646 } 647 648 @Override 649 public Drawable newDrawable(Resources res) { 650 return new NinePatchDrawable(this, res, null); 651 } 652 653 @Override 654 public Drawable newDrawable(Resources res, Theme theme) { 655 return new NinePatchDrawable(this, res, theme); 656 } 657 658 @Override 659 public int getChangingConfigurations() { 660 return mChangingConfigurations; 661 } 662 } 663 664 /** 665 * The one constructor to rule them all. This is called by all public 666 * constructors to set the state and initialize local properties. 667 */ 668 private NinePatchDrawable(NinePatchState state, Resources res, Theme theme) { 669 if (theme != null && state.canApplyTheme()) { 670 // If we need to apply a theme, implicitly mutate. 671 mNinePatchState = new NinePatchState(state); 672 applyTheme(theme); 673 } else { 674 mNinePatchState = state; 675 } 676 677 initializeWithState(state, res); 678 } 679 680 /** 681 * Initializes local dynamic properties from state. 682 */ 683 private void initializeWithState(NinePatchState state, Resources res) { 684 if (res != null) { 685 mTargetDensity = res.getDisplayMetrics().densityDpi; 686 } else { 687 mTargetDensity = state.mTargetDensity; 688 } 689 690 // If we can, avoid calling any methods that initialize Paint. 691 if (state.mDither != DEFAULT_DITHER) { 692 setDither(state.mDither); 693 } 694 695 // Make a local copy of the padding. 696 if (state.mPadding != null) { 697 mPadding = new Rect(state.mPadding); 698 } 699 700 mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode); 701 setNinePatch(state.mNinePatch); 702 } 703} 704