NinePatchDrawable.java revision cda212d79d449468384cc7744878b8c99984059c
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.content.res.ColorStateList; 20import android.content.res.Resources; 21import android.content.res.Resources.Theme; 22import android.content.res.TypedArray; 23import android.graphics.Bitmap; 24import android.graphics.BitmapFactory; 25import android.graphics.Canvas; 26import android.graphics.Color; 27import android.graphics.ColorFilter; 28import android.graphics.Insets; 29import android.graphics.NinePatch; 30import android.graphics.Paint; 31import android.graphics.Paint.Style; 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 /** 287 * @hide 288 */ 289 @Override 290 public Insets getOpticalInsets() { 291 if (needsMirroring()) { 292 return Insets.of(mOpticalInsets.right, mOpticalInsets.top, mOpticalInsets.right, 293 mOpticalInsets.bottom); 294 } else { 295 return mOpticalInsets; 296 } 297 } 298 299 @Override 300 public void setAlpha(int alpha) { 301 if (mPaint == null && alpha == 0xFF) { 302 // Fast common case -- leave at normal alpha. 303 return; 304 } 305 getPaint().setAlpha(alpha); 306 invalidateSelf(); 307 } 308 309 @Override 310 public int getAlpha() { 311 if (mPaint == null) { 312 // Fast common case -- normal alpha. 313 return 0xFF; 314 } 315 return getPaint().getAlpha(); 316 } 317 318 @Override 319 public void setColorFilter(ColorFilter cf) { 320 if (mPaint == null && cf == null) { 321 // Fast common case -- leave at no color filter. 322 return; 323 } 324 getPaint().setColorFilter(cf); 325 invalidateSelf(); 326 } 327 328 @Override 329 public void setTint(ColorStateList tint, PorterDuff.Mode tintMode) { 330 mNinePatchState.mTint = tint; 331 mNinePatchState.mTintMode = tintMode; 332 computeTintFilter(); 333 invalidateSelf(); 334 } 335 336 private void computeTintFilter() { 337 final NinePatchState state = mNinePatchState; 338 if (state.mTint != null && state.mTintMode != null) { 339 final int color = state.mTint.getColorForState(getState(), 0); 340 if (mTintFilter != null) { 341 mTintFilter.setColor(color); 342 mTintFilter.setMode(state.mTintMode); 343 } else { 344 mTintFilter = new PorterDuffColorFilter(color, state.mTintMode); 345 } 346 } else { 347 mTintFilter = null; 348 } 349 } 350 351 @Override 352 public void setDither(boolean dither) { 353 //noinspection PointlessBooleanExpression 354 if (mPaint == null && dither == DEFAULT_DITHER) { 355 // Fast common case -- leave at default dither. 356 return; 357 } 358 359 getPaint().setDither(dither); 360 invalidateSelf(); 361 } 362 363 @Override 364 public void setAutoMirrored(boolean mirrored) { 365 mNinePatchState.mAutoMirrored = mirrored; 366 } 367 368 private boolean needsMirroring() { 369 return isAutoMirrored() && getLayoutDirection() == LayoutDirection.RTL; 370 } 371 372 @Override 373 public boolean isAutoMirrored() { 374 return mNinePatchState.mAutoMirrored; 375 } 376 377 @Override 378 public void setFilterBitmap(boolean filter) { 379 getPaint().setFilterBitmap(filter); 380 invalidateSelf(); 381 } 382 383 @Override 384 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 385 throws XmlPullParserException, IOException { 386 super.inflate(r, parser, attrs, theme); 387 388 final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.NinePatchDrawable); 389 updateStateFromTypedArray(a); 390 a.recycle(); 391 } 392 393 /** 394 * Updates the constant state from the values in the typed array. 395 */ 396 private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException { 397 final Resources r = a.getResources(); 398 final NinePatchState state = mNinePatchState; 399 400 // Extract the theme attributes, if any. 401 final int[] themeAttrs = a.extractThemeAttrs(); 402 state.mThemeAttrs = themeAttrs; 403 404 state.mDither = a.getBoolean(R.styleable.NinePatchDrawable_dither, state.mDither); 405 406 final int srcResId = a.getResourceId(R.styleable.NinePatchDrawable_src, 0); 407 if (srcResId != 0) { 408 final BitmapFactory.Options options = new BitmapFactory.Options(); 409 options.inDither = !state.mDither; 410 options.inScreenDensity = r.getDisplayMetrics().noncompatDensityDpi; 411 412 final Rect padding = new Rect(); 413 final Rect opticalInsets = new Rect(); 414 Bitmap bitmap = null; 415 416 try { 417 final TypedValue value = new TypedValue(); 418 final InputStream is = r.openRawResource(srcResId, value); 419 420 bitmap = BitmapFactory.decodeResourceStream(r, value, is, padding, options); 421 422 is.close(); 423 } catch (IOException e) { 424 // Ignore 425 } 426 427 if (bitmap == null) { 428 throw new XmlPullParserException(a.getPositionDescription() + 429 ": <nine-patch> requires a valid src attribute"); 430 } else if (bitmap.getNinePatchChunk() == null) { 431 throw new XmlPullParserException(a.getPositionDescription() + 432 ": <nine-patch> requires a valid 9-patch source image"); 433 } 434 435 state.mNinePatch = new NinePatch(bitmap, bitmap.getNinePatchChunk()); 436 state.mPadding = padding; 437 state.mOpticalInsets = Insets.of(opticalInsets); 438 } 439 440 state.mAutoMirrored = a.getBoolean( 441 R.styleable.NinePatchDrawable_autoMirrored, state.mAutoMirrored); 442 state.mBaseAlpha = a.getFloat(R.styleable.NinePatchDrawable_alpha, state.mBaseAlpha); 443 444 final int tintMode = a.getInt(R.styleable.NinePatchDrawable_tintMode, -1); 445 if (tintMode != -1) { 446 state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN); 447 } 448 449 final ColorStateList tint = a.getColorStateList(R.styleable.NinePatchDrawable_tint); 450 if (tint != null) { 451 state.mTint = tint; 452 } 453 454 // Update local properties. 455 initializeWithState(state, r); 456 457 // Push density applied by setNinePatchState into state. 458 state.mTargetDensity = mTargetDensity; 459 } 460 461 @Override 462 public void applyTheme(Theme t) { 463 super.applyTheme(t); 464 465 final NinePatchState state = mNinePatchState; 466 if (state == null || state.mThemeAttrs == null) { 467 return; 468 } 469 470 final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.NinePatchDrawable); 471 try { 472 updateStateFromTypedArray(a); 473 } catch (XmlPullParserException e) { 474 throw new RuntimeException(e); 475 } finally { 476 a.recycle(); 477 } 478 } 479 480 @Override 481 public boolean canApplyTheme() { 482 return mNinePatchState != null && mNinePatchState.mThemeAttrs != null; 483 } 484 485 public Paint getPaint() { 486 if (mPaint == null) { 487 mPaint = new Paint(); 488 mPaint.setDither(DEFAULT_DITHER); 489 } 490 return mPaint; 491 } 492 493 /** 494 * Retrieves the width of the source .png file (before resizing). 495 */ 496 @Override 497 public int getIntrinsicWidth() { 498 return mBitmapWidth; 499 } 500 501 /** 502 * Retrieves the height of the source .png file (before resizing). 503 */ 504 @Override 505 public int getIntrinsicHeight() { 506 return mBitmapHeight; 507 } 508 509 @Override 510 public int getMinimumWidth() { 511 return mBitmapWidth; 512 } 513 514 @Override 515 public int getMinimumHeight() { 516 return mBitmapHeight; 517 } 518 519 /** 520 * Returns a {@link android.graphics.PixelFormat graphics.PixelFormat} 521 * value of OPAQUE or TRANSLUCENT. 522 */ 523 @Override 524 public int getOpacity() { 525 return mNinePatch.hasAlpha() || (mPaint != null && mPaint.getAlpha() < 255) ? 526 PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; 527 } 528 529 @Override 530 public Region getTransparentRegion() { 531 return mNinePatch.getTransparentRegion(getBounds()); 532 } 533 534 @Override 535 public ConstantState getConstantState() { 536 mNinePatchState.mChangingConfigurations = getChangingConfigurations(); 537 return mNinePatchState; 538 } 539 540 @Override 541 public Drawable mutate() { 542 if (!mMutated && super.mutate() == this) { 543 mNinePatchState = new NinePatchState(mNinePatchState); 544 mNinePatch = mNinePatchState.mNinePatch; 545 mMutated = true; 546 } 547 return this; 548 } 549 550 @Override 551 protected boolean onStateChange(int[] stateSet) { 552 final ColorStateList tint = mNinePatchState.mTint; 553 if (tint != null) { 554 final int newColor = tint.getColorForState(stateSet, 0); 555 final int oldColor = mTintFilter.getColor(); 556 if (oldColor != newColor) { 557 mTintFilter.setColor(newColor); 558 invalidateSelf(); 559 return true; 560 } 561 } 562 563 return false; 564 } 565 566 @Override 567 public boolean isStateful() { 568 final NinePatchState s = mNinePatchState; 569 return super.isStateful() || (s.mTint != null && s.mTint.isStateful()); 570 } 571 572 final static class NinePatchState extends ConstantState { 573 // Values loaded during inflation. 574 int[] mThemeAttrs = null; 575 NinePatch mNinePatch = null; 576 ColorStateList mTint = null; 577 Mode mTintMode = Mode.SRC_IN; 578 Rect mPadding = null; 579 Insets mOpticalInsets = Insets.NONE; 580 float mBaseAlpha = 1.0f; 581 boolean mDither = DEFAULT_DITHER; 582 int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; 583 boolean mAutoMirrored = false; 584 585 int mChangingConfigurations; 586 587 NinePatchState() { 588 // Empty constructor. 589 } 590 591 NinePatchState(NinePatch ninePatch, Rect padding) { 592 this(ninePatch, padding, new Rect(), DEFAULT_DITHER, false); 593 } 594 595 NinePatchState(NinePatch ninePatch, Rect padding, Rect opticalInsets) { 596 this(ninePatch, padding, opticalInsets, DEFAULT_DITHER, false); 597 } 598 599 NinePatchState(NinePatch ninePatch, Rect rect, Rect opticalInsets, boolean dither, 600 boolean autoMirror) { 601 mNinePatch = ninePatch; 602 mPadding = rect; 603 mOpticalInsets = Insets.of(opticalInsets); 604 mDither = dither; 605 mAutoMirrored = autoMirror; 606 } 607 608 // Copy constructor 609 610 NinePatchState(NinePatchState state) { 611 // We don't deep-copy any fields because they are all immutable. 612 mNinePatch = state.mNinePatch; 613 mTint = state.mTint; 614 mTintMode = state.mTintMode; 615 mThemeAttrs = state.mThemeAttrs; 616 mPadding = state.mPadding; 617 mOpticalInsets = state.mOpticalInsets; 618 mBaseAlpha = state.mBaseAlpha; 619 mDither = state.mDither; 620 mChangingConfigurations = state.mChangingConfigurations; 621 mTargetDensity = state.mTargetDensity; 622 mAutoMirrored = state.mAutoMirrored; 623 } 624 625 @Override 626 public boolean canApplyTheme() { 627 return mThemeAttrs != null; 628 } 629 630 @Override 631 public Bitmap getBitmap() { 632 return mNinePatch.getBitmap(); 633 } 634 635 @Override 636 public Drawable newDrawable() { 637 return new NinePatchDrawable(this, null, null); 638 } 639 640 @Override 641 public Drawable newDrawable(Resources res) { 642 return new NinePatchDrawable(this, res, null); 643 } 644 645 @Override 646 public Drawable newDrawable(Resources res, Theme theme) { 647 return new NinePatchDrawable(this, res, theme); 648 } 649 650 @Override 651 public int getChangingConfigurations() { 652 return mChangingConfigurations; 653 } 654 } 655 656 /** 657 * The one constructor to rule them all. This is called by all public 658 * constructors to set the state and initialize local properties. 659 */ 660 private NinePatchDrawable(NinePatchState state, Resources res, Theme theme) { 661 if (theme != null && state.canApplyTheme()) { 662 // If we need to apply a theme, implicitly mutate. 663 mNinePatchState = new NinePatchState(state); 664 applyTheme(theme); 665 } else { 666 mNinePatchState = state; 667 } 668 669 initializeWithState(state, res); 670 } 671 672 /** 673 * Initializes local dynamic properties from state. 674 */ 675 private void initializeWithState(NinePatchState state, Resources res) { 676 if (res != null) { 677 mTargetDensity = res.getDisplayMetrics().densityDpi; 678 } else { 679 mTargetDensity = state.mTargetDensity; 680 } 681 682 // If we can, avoid calling any methods that initialize Paint. 683 if (state.mDither != DEFAULT_DITHER) { 684 setDither(state.mDither); 685 } 686 687 // Make a local copy of the padding. 688 if (state.mPadding != null) { 689 mPadding = new Rect(state.mPadding); 690 } 691 692 computeTintFilter(); 693 setNinePatch(state.mNinePatch); 694 } 695} 696