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