Bitmap.java revision 3bdecbf0fd2d4b6137477094e1ea96502c353248
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; 18 19import android.annotation.CheckResult; 20import android.annotation.ColorInt; 21import android.annotation.NonNull; 22import android.os.Parcel; 23import android.os.Parcelable; 24import android.os.Trace; 25import android.util.DisplayMetrics; 26import android.util.Log; 27 28import libcore.util.NativeAllocationRegistry; 29 30import java.io.OutputStream; 31import java.nio.Buffer; 32import java.nio.ByteBuffer; 33import java.nio.IntBuffer; 34import java.nio.ShortBuffer; 35 36public final class Bitmap implements Parcelable { 37 private static final String TAG = "Bitmap"; 38 39 /** 40 * Indicates that the bitmap was created for an unknown pixel density. 41 * 42 * @see Bitmap#getDensity() 43 * @see Bitmap#setDensity(int) 44 */ 45 public static final int DENSITY_NONE = 0; 46 47 // Estimated size of the Bitmap native allocation, not including 48 // pixel data. 49 private static final long NATIVE_ALLOCATION_SIZE = 32; 50 51 // Convenience for JNI access 52 private final long mNativePtr; 53 54 private final boolean mIsMutable; 55 56 /** 57 * Represents whether the Bitmap's content is requested to be pre-multiplied. 58 * Note that isPremultiplied() does not directly return this value, because 59 * isPremultiplied() may never return true for a 565 Bitmap or a bitmap 60 * without alpha. 61 * 62 * setPremultiplied() does directly set the value so that setConfig() and 63 * setPremultiplied() aren't order dependent, despite being setters. 64 * 65 * The native bitmap's premultiplication state is kept up to date by 66 * pushing down this preference for every config change. 67 */ 68 private boolean mRequestPremultiplied; 69 70 private byte[] mNinePatchChunk; // may be null 71 private NinePatch.InsetStruct mNinePatchInsets; // may be null 72 private int mWidth; 73 private int mHeight; 74 private boolean mRecycled; 75 76 /** @hide */ 77 public int mDensity = getDefaultDensity(); 78 79 private static volatile Matrix sScaleMatrix; 80 81 private static volatile int sDefaultDensity = -1; 82 83 /** 84 * For backwards compatibility, allows the app layer to change the default 85 * density when running old apps. 86 * @hide 87 */ 88 public static void setDefaultDensity(int density) { 89 sDefaultDensity = density; 90 } 91 92 @SuppressWarnings("deprecation") 93 static int getDefaultDensity() { 94 if (sDefaultDensity >= 0) { 95 return sDefaultDensity; 96 } 97 sDefaultDensity = DisplayMetrics.DENSITY_DEVICE; 98 return sDefaultDensity; 99 } 100 101 /** 102 * Private constructor that must received an already allocated native bitmap 103 * int (pointer). 104 */ 105 // called from JNI 106 Bitmap(long nativeBitmap, int width, int height, int density, 107 boolean isMutable, boolean requestPremultiplied, 108 byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets) { 109 if (nativeBitmap == 0) { 110 throw new RuntimeException("internal error: native bitmap is 0"); 111 } 112 113 mWidth = width; 114 mHeight = height; 115 mIsMutable = isMutable; 116 mRequestPremultiplied = requestPremultiplied; 117 118 mNinePatchChunk = ninePatchChunk; 119 mNinePatchInsets = ninePatchInsets; 120 if (density >= 0) { 121 mDensity = density; 122 } 123 124 mNativePtr = nativeBitmap; 125 long nativeSize = NATIVE_ALLOCATION_SIZE + getAllocationByteCount(); 126 NativeAllocationRegistry registry = new NativeAllocationRegistry( 127 Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), nativeSize); 128 registry.registerNativeAllocation(this, nativeBitmap); 129 } 130 131 /** 132 * Return the pointer to the native object. 133 * @hide 134 */ 135 public long getNativeInstance() { 136 return mNativePtr; 137 } 138 139 /** 140 * Native bitmap has been reconfigured, so set premult and cached 141 * width/height values 142 */ 143 // called from JNI 144 void reinit(int width, int height, boolean requestPremultiplied) { 145 mWidth = width; 146 mHeight = height; 147 mRequestPremultiplied = requestPremultiplied; 148 } 149 150 /** 151 * <p>Returns the density for this bitmap.</p> 152 * 153 * <p>The default density is the same density as the current display, 154 * unless the current application does not support different screen 155 * densities in which case it is 156 * {@link android.util.DisplayMetrics#DENSITY_DEFAULT}. Note that 157 * compatibility mode is determined by the application that was initially 158 * loaded into a process -- applications that share the same process should 159 * all have the same compatibility, or ensure they explicitly set the 160 * density of their bitmaps appropriately.</p> 161 * 162 * @return A scaling factor of the default density or {@link #DENSITY_NONE} 163 * if the scaling factor is unknown. 164 * 165 * @see #setDensity(int) 166 * @see android.util.DisplayMetrics#DENSITY_DEFAULT 167 * @see android.util.DisplayMetrics#densityDpi 168 * @see #DENSITY_NONE 169 */ 170 public int getDensity() { 171 if (mRecycled) { 172 Log.w(TAG, "Called getDensity() on a recycle()'d bitmap! This is undefined behavior!"); 173 } 174 return mDensity; 175 } 176 177 /** 178 * <p>Specifies the density for this bitmap. When the bitmap is 179 * drawn to a Canvas that also has a density, it will be scaled 180 * appropriately.</p> 181 * 182 * @param density The density scaling factor to use with this bitmap or 183 * {@link #DENSITY_NONE} if the density is unknown. 184 * 185 * @see #getDensity() 186 * @see android.util.DisplayMetrics#DENSITY_DEFAULT 187 * @see android.util.DisplayMetrics#densityDpi 188 * @see #DENSITY_NONE 189 */ 190 public void setDensity(int density) { 191 mDensity = density; 192 } 193 194 /** 195 * <p>Modifies the bitmap to have a specified width, height, and {@link 196 * Config}, without affecting the underlying allocation backing the bitmap. 197 * Bitmap pixel data is not re-initialized for the new configuration.</p> 198 * 199 * <p>This method can be used to avoid allocating a new bitmap, instead 200 * reusing an existing bitmap's allocation for a new configuration of equal 201 * or lesser size. If the Bitmap's allocation isn't large enough to support 202 * the new configuration, an IllegalArgumentException will be thrown and the 203 * bitmap will not be modified.</p> 204 * 205 * <p>The result of {@link #getByteCount()} will reflect the new configuration, 206 * while {@link #getAllocationByteCount()} will reflect that of the initial 207 * configuration.</p> 208 * 209 * <p>Note: This may change this result of hasAlpha(). When converting to 565, 210 * the new bitmap will always be considered opaque. When converting from 565, 211 * the new bitmap will be considered non-opaque, and will respect the value 212 * set by setPremultiplied().</p> 213 * 214 * <p>WARNING: This method should NOT be called on a bitmap currently in use 215 * by the view system, Canvas, or the AndroidBitmap NDK API. It does not 216 * make guarantees about how the underlying pixel buffer is remapped to the 217 * new config, just that the allocation is reused. Additionally, the view 218 * system does not account for bitmap properties being modifying during use, 219 * e.g. while attached to drawables.</p> 220 * 221 * <p>In order to safely ensure that a Bitmap is no longer in use by the 222 * View system it is necessary to wait for a draw pass to occur after 223 * invalidate()'ing any view that had previously drawn the Bitmap in the last 224 * draw pass due to hardware acceleration's caching of draw commands. As 225 * an example, here is how this can be done for an ImageView: 226 * <pre class="prettyprint"> 227 * ImageView myImageView = ...; 228 * final Bitmap myBitmap = ...; 229 * myImageView.setImageDrawable(null); 230 * myImageView.post(new Runnable() { 231 * public void run() { 232 * // myBitmap is now no longer in use by the ImageView 233 * // and can be safely reconfigured. 234 * myBitmap.reconfigure(...); 235 * } 236 * }); 237 * </pre></p> 238 * 239 * @see #setWidth(int) 240 * @see #setHeight(int) 241 * @see #setConfig(Config) 242 */ 243 public void reconfigure(int width, int height, Config config) { 244 checkRecycled("Can't call reconfigure() on a recycled bitmap"); 245 if (width <= 0 || height <= 0) { 246 throw new IllegalArgumentException("width and height must be > 0"); 247 } 248 if (!isMutable()) { 249 throw new IllegalStateException("only mutable bitmaps may be reconfigured"); 250 } 251 252 nativeReconfigure(mNativePtr, width, height, config.nativeInt, mRequestPremultiplied); 253 mWidth = width; 254 mHeight = height; 255 } 256 257 /** 258 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 259 * with the current height and config.</p> 260 * 261 * <p>WARNING: this method should not be used on bitmaps currently used by 262 * the view system, see {@link #reconfigure(int, int, Config)} for more 263 * details.</p> 264 * 265 * @see #reconfigure(int, int, Config) 266 * @see #setHeight(int) 267 * @see #setConfig(Config) 268 */ 269 public void setWidth(int width) { 270 reconfigure(width, getHeight(), getConfig()); 271 } 272 273 /** 274 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 275 * with the current width and config.</p> 276 * 277 * <p>WARNING: this method should not be used on bitmaps currently used by 278 * the view system, see {@link #reconfigure(int, int, Config)} for more 279 * details.</p> 280 * 281 * @see #reconfigure(int, int, Config) 282 * @see #setWidth(int) 283 * @see #setConfig(Config) 284 */ 285 public void setHeight(int height) { 286 reconfigure(getWidth(), height, getConfig()); 287 } 288 289 /** 290 * <p>Convenience method for calling {@link #reconfigure(int, int, Config)} 291 * with the current height and width.</p> 292 * 293 * <p>WARNING: this method should not be used on bitmaps currently used by 294 * the view system, see {@link #reconfigure(int, int, Config)} for more 295 * details.</p> 296 * 297 * @see #reconfigure(int, int, Config) 298 * @see #setWidth(int) 299 * @see #setHeight(int) 300 */ 301 public void setConfig(Config config) { 302 reconfigure(getWidth(), getHeight(), config); 303 } 304 305 /** 306 * Sets the nine patch chunk. 307 * 308 * @param chunk The definition of the nine patch 309 * 310 * @hide 311 */ 312 public void setNinePatchChunk(byte[] chunk) { 313 mNinePatchChunk = chunk; 314 } 315 316 /** 317 * Free the native object associated with this bitmap, and clear the 318 * reference to the pixel data. This will not free the pixel data synchronously; 319 * it simply allows it to be garbage collected if there are no other references. 320 * The bitmap is marked as "dead", meaning it will throw an exception if 321 * getPixels() or setPixels() is called, and will draw nothing. This operation 322 * cannot be reversed, so it should only be called if you are sure there are no 323 * further uses for the bitmap. This is an advanced call, and normally need 324 * not be called, since the normal GC process will free up this memory when 325 * there are no more references to this bitmap. 326 */ 327 public void recycle() { 328 if (!mRecycled && mNativePtr != 0) { 329 if (nativeRecycle(mNativePtr)) { 330 // return value indicates whether native pixel object was actually recycled. 331 // false indicates that it is still in use at the native level and these 332 // objects should not be collected now. They will be collected later when the 333 // Bitmap itself is collected. 334 mNinePatchChunk = null; 335 } 336 mRecycled = true; 337 } 338 } 339 340 /** 341 * Returns true if this bitmap has been recycled. If so, then it is an error 342 * to try to access its pixels, and the bitmap will not draw. 343 * 344 * @return true if the bitmap has been recycled 345 */ 346 public final boolean isRecycled() { 347 return mRecycled; 348 } 349 350 /** 351 * Returns the generation ID of this bitmap. The generation ID changes 352 * whenever the bitmap is modified. This can be used as an efficient way to 353 * check if a bitmap has changed. 354 * 355 * @return The current generation ID for this bitmap. 356 */ 357 public int getGenerationId() { 358 if (mRecycled) { 359 Log.w(TAG, "Called getGenerationId() on a recycle()'d bitmap! This is undefined behavior!"); 360 } 361 return nativeGenerationId(mNativePtr); 362 } 363 364 /** 365 * This is called by methods that want to throw an exception if the bitmap 366 * has already been recycled. 367 */ 368 private void checkRecycled(String errorMessage) { 369 if (mRecycled) { 370 throw new IllegalStateException(errorMessage); 371 } 372 } 373 374 /** 375 * Common code for checking that x and y are >= 0 376 * 377 * @param x x coordinate to ensure is >= 0 378 * @param y y coordinate to ensure is >= 0 379 */ 380 private static void checkXYSign(int x, int y) { 381 if (x < 0) { 382 throw new IllegalArgumentException("x must be >= 0"); 383 } 384 if (y < 0) { 385 throw new IllegalArgumentException("y must be >= 0"); 386 } 387 } 388 389 /** 390 * Common code for checking that width and height are > 0 391 * 392 * @param width width to ensure is > 0 393 * @param height height to ensure is > 0 394 */ 395 private static void checkWidthHeight(int width, int height) { 396 if (width <= 0) { 397 throw new IllegalArgumentException("width must be > 0"); 398 } 399 if (height <= 0) { 400 throw new IllegalArgumentException("height must be > 0"); 401 } 402 } 403 404 /** 405 * Possible bitmap configurations. A bitmap configuration describes 406 * how pixels are stored. This affects the quality (color depth) as 407 * well as the ability to display transparent/translucent colors. 408 */ 409 public enum Config { 410 // these native values must match up with the enum in SkBitmap.h 411 412 /** 413 * Each pixel is stored as a single translucency (alpha) channel. 414 * This is very useful to efficiently store masks for instance. 415 * No color information is stored. 416 * With this configuration, each pixel requires 1 byte of memory. 417 */ 418 ALPHA_8 (1), 419 420 /** 421 * Each pixel is stored on 2 bytes and only the RGB channels are 422 * encoded: red is stored with 5 bits of precision (32 possible 423 * values), green is stored with 6 bits of precision (64 possible 424 * values) and blue is stored with 5 bits of precision. 425 * 426 * This configuration can produce slight visual artifacts depending 427 * on the configuration of the source. For instance, without 428 * dithering, the result might show a greenish tint. To get better 429 * results dithering should be applied. 430 * 431 * This configuration may be useful when using opaque bitmaps 432 * that do not require high color fidelity. 433 */ 434 RGB_565 (3), 435 436 /** 437 * Each pixel is stored on 2 bytes. The three RGB color channels 438 * and the alpha channel (translucency) are stored with a 4 bits 439 * precision (16 possible values.) 440 * 441 * This configuration is mostly useful if the application needs 442 * to store translucency information but also needs to save 443 * memory. 444 * 445 * It is recommended to use {@link #ARGB_8888} instead of this 446 * configuration. 447 * 448 * Note: as of {@link android.os.Build.VERSION_CODES#KITKAT}, 449 * any bitmap created with this configuration will be created 450 * using {@link #ARGB_8888} instead. 451 * 452 * @deprecated Because of the poor quality of this configuration, 453 * it is advised to use {@link #ARGB_8888} instead. 454 */ 455 @Deprecated 456 ARGB_4444 (4), 457 458 /** 459 * Each pixel is stored on 4 bytes. Each channel (RGB and alpha 460 * for translucency) is stored with 8 bits of precision (256 461 * possible values.) 462 * 463 * This configuration is very flexible and offers the best 464 * quality. It should be used whenever possible. 465 */ 466 ARGB_8888 (5); 467 468 final int nativeInt; 469 470 private static Config sConfigs[] = { 471 null, ALPHA_8, null, RGB_565, ARGB_4444, ARGB_8888 472 }; 473 474 Config(int ni) { 475 this.nativeInt = ni; 476 } 477 478 static Config nativeToConfig(int ni) { 479 return sConfigs[ni]; 480 } 481 } 482 483 /** 484 * <p>Copy the bitmap's pixels into the specified buffer (allocated by the 485 * caller). An exception is thrown if the buffer is not large enough to 486 * hold all of the pixels (taking into account the number of bytes per 487 * pixel) or if the Buffer subclass is not one of the support types 488 * (ByteBuffer, ShortBuffer, IntBuffer).</p> 489 * <p>The content of the bitmap is copied into the buffer as-is. This means 490 * that if this bitmap stores its pixels pre-multiplied 491 * (see {@link #isPremultiplied()}, the values in the buffer will also be 492 * pre-multiplied.</p> 493 * <p>After this method returns, the current position of the buffer is 494 * updated: the position is incremented by the number of elements written 495 * in the buffer.</p> 496 */ 497 public void copyPixelsToBuffer(Buffer dst) { 498 int elements = dst.remaining(); 499 int shift; 500 if (dst instanceof ByteBuffer) { 501 shift = 0; 502 } else if (dst instanceof ShortBuffer) { 503 shift = 1; 504 } else if (dst instanceof IntBuffer) { 505 shift = 2; 506 } else { 507 throw new RuntimeException("unsupported Buffer subclass"); 508 } 509 510 long bufferSize = (long)elements << shift; 511 long pixelSize = getByteCount(); 512 513 if (bufferSize < pixelSize) { 514 throw new RuntimeException("Buffer not large enough for pixels"); 515 } 516 517 nativeCopyPixelsToBuffer(mNativePtr, dst); 518 519 // now update the buffer's position 520 int position = dst.position(); 521 position += pixelSize >> shift; 522 dst.position(position); 523 } 524 525 /** 526 * <p>Copy the pixels from the buffer, beginning at the current position, 527 * overwriting the bitmap's pixels. The data in the buffer is not changed 528 * in any way (unlike setPixels(), which converts from unpremultipled 32bit 529 * to whatever the bitmap's native format is.</p> 530 * <p>After this method returns, the current position of the buffer is 531 * updated: the position is incremented by the number of elements read from 532 * the buffer. If you need to read the bitmap from the buffer again you must 533 * first rewind the buffer.</p> 534 */ 535 public void copyPixelsFromBuffer(Buffer src) { 536 checkRecycled("copyPixelsFromBuffer called on recycled bitmap"); 537 538 int elements = src.remaining(); 539 int shift; 540 if (src instanceof ByteBuffer) { 541 shift = 0; 542 } else if (src instanceof ShortBuffer) { 543 shift = 1; 544 } else if (src instanceof IntBuffer) { 545 shift = 2; 546 } else { 547 throw new RuntimeException("unsupported Buffer subclass"); 548 } 549 550 long bufferBytes = (long) elements << shift; 551 long bitmapBytes = getByteCount(); 552 553 if (bufferBytes < bitmapBytes) { 554 throw new RuntimeException("Buffer not large enough for pixels"); 555 } 556 557 nativeCopyPixelsFromBuffer(mNativePtr, src); 558 559 // now update the buffer's position 560 int position = src.position(); 561 position += bitmapBytes >> shift; 562 src.position(position); 563 } 564 565 /** 566 * Tries to make a new bitmap based on the dimensions of this bitmap, 567 * setting the new bitmap's config to the one specified, and then copying 568 * this bitmap's pixels into the new bitmap. If the conversion is not 569 * supported, or the allocator fails, then this returns NULL. The returned 570 * bitmap initially has the same density as the original. 571 * 572 * @param config The desired config for the resulting bitmap 573 * @param isMutable True if the resulting bitmap should be mutable (i.e. 574 * its pixels can be modified) 575 * @return the new bitmap, or null if the copy could not be made. 576 */ 577 public Bitmap copy(Config config, boolean isMutable) { 578 checkRecycled("Can't copy a recycled bitmap"); 579 Bitmap b = nativeCopy(mNativePtr, config.nativeInt, isMutable); 580 if (b != null) { 581 b.setPremultiplied(mRequestPremultiplied); 582 b.mDensity = mDensity; 583 } 584 return b; 585 } 586 587 /** 588 * Creates a new immutable bitmap backed by ashmem which can efficiently 589 * be passed between processes. 590 * 591 * @hide 592 */ 593 public Bitmap createAshmemBitmap() { 594 checkRecycled("Can't copy a recycled bitmap"); 595 Bitmap b = nativeCopyAshmem(mNativePtr); 596 if (b != null) { 597 b.setPremultiplied(mRequestPremultiplied); 598 b.mDensity = mDensity; 599 } 600 return b; 601 } 602 603 /** 604 * Creates a new immutable bitmap backed by ashmem which can efficiently 605 * be passed between processes. 606 * 607 * @hide 608 */ 609 public Bitmap createAshmemBitmap(Config config) { 610 checkRecycled("Can't copy a recycled bitmap"); 611 Bitmap b = nativeCopyAshmemConfig(mNativePtr, config.nativeInt); 612 if (b != null) { 613 b.setPremultiplied(mRequestPremultiplied); 614 b.mDensity = mDensity; 615 } 616 return b; 617 } 618 619 /** 620 * Creates a new bitmap, scaled from an existing bitmap, when possible. If the 621 * specified width and height are the same as the current width and height of 622 * the source bitmap, the source bitmap is returned and no new bitmap is 623 * created. 624 * 625 * @param src The source bitmap. 626 * @param dstWidth The new bitmap's desired width. 627 * @param dstHeight The new bitmap's desired height. 628 * @param filter true if the source should be filtered. 629 * @return The new scaled bitmap or the source bitmap if no scaling is required. 630 * @throws IllegalArgumentException if width is <= 0, or height is <= 0 631 */ 632 public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, 633 boolean filter) { 634 Matrix m; 635 synchronized (Bitmap.class) { 636 // small pool of just 1 matrix 637 m = sScaleMatrix; 638 sScaleMatrix = null; 639 } 640 641 if (m == null) { 642 m = new Matrix(); 643 } 644 645 final int width = src.getWidth(); 646 final int height = src.getHeight(); 647 final float sx = dstWidth / (float)width; 648 final float sy = dstHeight / (float)height; 649 m.setScale(sx, sy); 650 Bitmap b = Bitmap.createBitmap(src, 0, 0, width, height, m, filter); 651 652 synchronized (Bitmap.class) { 653 // do we need to check for null? why not just assign everytime? 654 if (sScaleMatrix == null) { 655 sScaleMatrix = m; 656 } 657 } 658 659 return b; 660 } 661 662 /** 663 * Returns an immutable bitmap from the source bitmap. The new bitmap may 664 * be the same object as source, or a copy may have been made. It is 665 * initialized with the same density as the original bitmap. 666 */ 667 public static Bitmap createBitmap(Bitmap src) { 668 return createBitmap(src, 0, 0, src.getWidth(), src.getHeight()); 669 } 670 671 /** 672 * Returns an immutable bitmap from the specified subset of the source 673 * bitmap. The new bitmap may be the same object as source, or a copy may 674 * have been made. It is initialized with the same density as the original 675 * bitmap. 676 * 677 * @param source The bitmap we are subsetting 678 * @param x The x coordinate of the first pixel in source 679 * @param y The y coordinate of the first pixel in source 680 * @param width The number of pixels in each row 681 * @param height The number of rows 682 * @return A copy of a subset of the source bitmap or the source bitmap itself. 683 * @throws IllegalArgumentException if the x, y, width, height values are 684 * outside of the dimensions of the source bitmap, or width is <= 0, 685 * or height is <= 0 686 */ 687 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height) { 688 return createBitmap(source, x, y, width, height, null, false); 689 } 690 691 /** 692 * Returns an immutable bitmap from subset of the source bitmap, 693 * transformed by the optional matrix. The new bitmap may be the 694 * same object as source, or a copy may have been made. It is 695 * initialized with the same density as the original bitmap. 696 * 697 * If the source bitmap is immutable and the requested subset is the 698 * same as the source bitmap itself, then the source bitmap is 699 * returned and no new bitmap is created. 700 * 701 * @param source The bitmap we are subsetting 702 * @param x The x coordinate of the first pixel in source 703 * @param y The y coordinate of the first pixel in source 704 * @param width The number of pixels in each row 705 * @param height The number of rows 706 * @param m Optional matrix to be applied to the pixels 707 * @param filter true if the source should be filtered. 708 * Only applies if the matrix contains more than just 709 * translation. 710 * @return A bitmap that represents the specified subset of source 711 * @throws IllegalArgumentException if the x, y, width, height values are 712 * outside of the dimensions of the source bitmap, or width is <= 0, 713 * or height is <= 0 714 */ 715 public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, 716 Matrix m, boolean filter) { 717 718 checkXYSign(x, y); 719 checkWidthHeight(width, height); 720 if (x + width > source.getWidth()) { 721 throw new IllegalArgumentException("x + width must be <= bitmap.width()"); 722 } 723 if (y + height > source.getHeight()) { 724 throw new IllegalArgumentException("y + height must be <= bitmap.height()"); 725 } 726 727 // check if we can just return our argument unchanged 728 if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() && 729 height == source.getHeight() && (m == null || m.isIdentity())) { 730 return source; 731 } 732 733 int neww = width; 734 int newh = height; 735 Canvas canvas = new Canvas(); 736 Bitmap bitmap; 737 Paint paint; 738 739 Rect srcR = new Rect(x, y, x + width, y + height); 740 RectF dstR = new RectF(0, 0, width, height); 741 742 Config newConfig = Config.ARGB_8888; 743 final Config config = source.getConfig(); 744 // GIF files generate null configs, assume ARGB_8888 745 if (config != null) { 746 switch (config) { 747 case RGB_565: 748 newConfig = Config.RGB_565; 749 break; 750 case ALPHA_8: 751 newConfig = Config.ALPHA_8; 752 break; 753 //noinspection deprecation 754 case ARGB_4444: 755 case ARGB_8888: 756 default: 757 newConfig = Config.ARGB_8888; 758 break; 759 } 760 } 761 762 if (m == null || m.isIdentity()) { 763 bitmap = createBitmap(neww, newh, newConfig, source.hasAlpha()); 764 paint = null; // not needed 765 } else { 766 final boolean transformed = !m.rectStaysRect(); 767 768 RectF deviceR = new RectF(); 769 m.mapRect(deviceR, dstR); 770 771 neww = Math.round(deviceR.width()); 772 newh = Math.round(deviceR.height()); 773 774 bitmap = createBitmap(neww, newh, transformed ? Config.ARGB_8888 : newConfig, 775 transformed || source.hasAlpha()); 776 777 canvas.translate(-deviceR.left, -deviceR.top); 778 canvas.concat(m); 779 780 paint = new Paint(); 781 paint.setFilterBitmap(filter); 782 if (transformed) { 783 paint.setAntiAlias(true); 784 } 785 } 786 787 // The new bitmap was created from a known bitmap source so assume that 788 // they use the same density 789 bitmap.mDensity = source.mDensity; 790 bitmap.setHasAlpha(source.hasAlpha()); 791 bitmap.setPremultiplied(source.mRequestPremultiplied); 792 793 canvas.setBitmap(bitmap); 794 canvas.drawBitmap(source, srcR, dstR, paint); 795 canvas.setBitmap(null); 796 797 return bitmap; 798 } 799 800 /** 801 * Returns a mutable bitmap with the specified width and height. Its 802 * initial density is as per {@link #getDensity}. 803 * 804 * @param width The width of the bitmap 805 * @param height The height of the bitmap 806 * @param config The bitmap config to create. 807 * @throws IllegalArgumentException if the width or height are <= 0 808 */ 809 public static Bitmap createBitmap(int width, int height, Config config) { 810 return createBitmap(width, height, config, true); 811 } 812 813 /** 814 * Returns a mutable bitmap with the specified width and height. Its 815 * initial density is determined from the given {@link DisplayMetrics}. 816 * 817 * @param display Display metrics for the display this bitmap will be 818 * drawn on. 819 * @param width The width of the bitmap 820 * @param height The height of the bitmap 821 * @param config The bitmap config to create. 822 * @throws IllegalArgumentException if the width or height are <= 0 823 */ 824 public static Bitmap createBitmap(DisplayMetrics display, int width, 825 int height, Config config) { 826 return createBitmap(display, width, height, config, true); 827 } 828 829 /** 830 * Returns a mutable bitmap with the specified width and height. Its 831 * initial density is as per {@link #getDensity}. 832 * 833 * @param width The width of the bitmap 834 * @param height The height of the bitmap 835 * @param config The bitmap config to create. 836 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 837 * bitmap as opaque. Doing so will clear the bitmap in black 838 * instead of transparent. 839 * 840 * @throws IllegalArgumentException if the width or height are <= 0 841 */ 842 private static Bitmap createBitmap(int width, int height, Config config, boolean hasAlpha) { 843 return createBitmap(null, width, height, config, hasAlpha); 844 } 845 846 /** 847 * Returns a mutable bitmap with the specified width and height. Its 848 * initial density is determined from the given {@link DisplayMetrics}. 849 * 850 * @param display Display metrics for the display this bitmap will be 851 * drawn on. 852 * @param width The width of the bitmap 853 * @param height The height of the bitmap 854 * @param config The bitmap config to create. 855 * @param hasAlpha If the bitmap is ARGB_8888 this flag can be used to mark the 856 * bitmap as opaque. Doing so will clear the bitmap in black 857 * instead of transparent. 858 * 859 * @throws IllegalArgumentException if the width or height are <= 0 860 */ 861 private static Bitmap createBitmap(DisplayMetrics display, int width, int height, 862 Config config, boolean hasAlpha) { 863 if (width <= 0 || height <= 0) { 864 throw new IllegalArgumentException("width and height must be > 0"); 865 } 866 Bitmap bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true); 867 if (display != null) { 868 bm.mDensity = display.densityDpi; 869 } 870 bm.setHasAlpha(hasAlpha); 871 if (config == Config.ARGB_8888 && !hasAlpha) { 872 nativeErase(bm.mNativePtr, 0xff000000); 873 } 874 // No need to initialize the bitmap to zeroes with other configs; 875 // it is backed by a VM byte array which is by definition preinitialized 876 // to all zeroes. 877 return bm; 878 } 879 880 /** 881 * Returns a immutable bitmap with the specified width and height, with each 882 * pixel value set to the corresponding value in the colors array. Its 883 * initial density is as per {@link #getDensity}. 884 * 885 * @param colors Array of {@link Color} used to initialize the pixels. 886 * @param offset Number of values to skip before the first color in the 887 * array of colors. 888 * @param stride Number of colors in the array between rows (must be >= 889 * width or <= -width). 890 * @param width The width of the bitmap 891 * @param height The height of the bitmap 892 * @param config The bitmap config to create. If the config does not 893 * support per-pixel alpha (e.g. RGB_565), then the alpha 894 * bytes in the colors[] will be ignored (assumed to be FF) 895 * @throws IllegalArgumentException if the width or height are <= 0, or if 896 * the color array's length is less than the number of pixels. 897 */ 898 public static Bitmap createBitmap(int colors[], int offset, int stride, 899 int width, int height, Config config) { 900 return createBitmap(null, colors, offset, stride, width, height, config); 901 } 902 903 /** 904 * Returns a immutable bitmap with the specified width and height, with each 905 * pixel value set to the corresponding value in the colors array. Its 906 * initial density is determined from the given {@link DisplayMetrics}. 907 * 908 * @param display Display metrics for the display this bitmap will be 909 * drawn on. 910 * @param colors Array of {@link Color} used to initialize the pixels. 911 * @param offset Number of values to skip before the first color in the 912 * array of colors. 913 * @param stride Number of colors in the array between rows (must be >= 914 * width or <= -width). 915 * @param width The width of the bitmap 916 * @param height The height of the bitmap 917 * @param config The bitmap config to create. If the config does not 918 * support per-pixel alpha (e.g. RGB_565), then the alpha 919 * bytes in the colors[] will be ignored (assumed to be FF) 920 * @throws IllegalArgumentException if the width or height are <= 0, or if 921 * the color array's length is less than the number of pixels. 922 */ 923 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 924 int offset, int stride, int width, int height, Config config) { 925 926 checkWidthHeight(width, height); 927 if (Math.abs(stride) < width) { 928 throw new IllegalArgumentException("abs(stride) must be >= width"); 929 } 930 int lastScanline = offset + (height - 1) * stride; 931 int length = colors.length; 932 if (offset < 0 || (offset + width > length) || lastScanline < 0 || 933 (lastScanline + width > length)) { 934 throw new ArrayIndexOutOfBoundsException(); 935 } 936 if (width <= 0 || height <= 0) { 937 throw new IllegalArgumentException("width and height must be > 0"); 938 } 939 Bitmap bm = nativeCreate(colors, offset, stride, width, height, 940 config.nativeInt, false); 941 if (display != null) { 942 bm.mDensity = display.densityDpi; 943 } 944 return bm; 945 } 946 947 /** 948 * Returns a immutable bitmap with the specified width and height, with each 949 * pixel value set to the corresponding value in the colors array. Its 950 * initial density is as per {@link #getDensity}. 951 * 952 * @param colors Array of {@link Color} used to initialize the pixels. 953 * This array must be at least as large as width * height. 954 * @param width The width of the bitmap 955 * @param height The height of the bitmap 956 * @param config The bitmap config to create. If the config does not 957 * support per-pixel alpha (e.g. RGB_565), then the alpha 958 * bytes in the colors[] will be ignored (assumed to be FF) 959 * @throws IllegalArgumentException if the width or height are <= 0, or if 960 * the color array's length is less than the number of pixels. 961 */ 962 public static Bitmap createBitmap(int colors[], int width, int height, Config config) { 963 return createBitmap(null, colors, 0, width, width, height, config); 964 } 965 966 /** 967 * Returns a immutable bitmap with the specified width and height, with each 968 * pixel value set to the corresponding value in the colors array. Its 969 * initial density is determined from the given {@link DisplayMetrics}. 970 * 971 * @param display Display metrics for the display this bitmap will be 972 * drawn on. 973 * @param colors Array of {@link Color} used to initialize the pixels. 974 * This array must be at least as large as width * height. 975 * @param width The width of the bitmap 976 * @param height The height of the bitmap 977 * @param config The bitmap config to create. If the config does not 978 * support per-pixel alpha (e.g. RGB_565), then the alpha 979 * bytes in the colors[] will be ignored (assumed to be FF) 980 * @throws IllegalArgumentException if the width or height are <= 0, or if 981 * the color array's length is less than the number of pixels. 982 */ 983 public static Bitmap createBitmap(DisplayMetrics display, int colors[], 984 int width, int height, Config config) { 985 return createBitmap(display, colors, 0, width, width, height, config); 986 } 987 988 /** 989 * Returns an optional array of private data, used by the UI system for 990 * some bitmaps. Not intended to be called by applications. 991 */ 992 public byte[] getNinePatchChunk() { 993 return mNinePatchChunk; 994 } 995 996 /** 997 * Populates a rectangle with the bitmap's optical insets. 998 * 999 * @param outInsets Rect to populate with optical insets 1000 * @hide 1001 */ 1002 public void getOpticalInsets(@NonNull Rect outInsets) { 1003 if (mNinePatchInsets == null) { 1004 outInsets.setEmpty(); 1005 } else { 1006 outInsets.set(mNinePatchInsets.opticalRect); 1007 } 1008 } 1009 1010 /** @hide */ 1011 public NinePatch.InsetStruct getNinePatchInsets() { 1012 return mNinePatchInsets; 1013 } 1014 1015 /** 1016 * Specifies the known formats a bitmap can be compressed into 1017 */ 1018 public enum CompressFormat { 1019 JPEG (0), 1020 PNG (1), 1021 WEBP (2); 1022 1023 CompressFormat(int nativeInt) { 1024 this.nativeInt = nativeInt; 1025 } 1026 final int nativeInt; 1027 } 1028 1029 /** 1030 * Number of bytes of temp storage we use for communicating between the 1031 * native compressor and the java OutputStream. 1032 */ 1033 private final static int WORKING_COMPRESS_STORAGE = 4096; 1034 1035 /** 1036 * Write a compressed version of the bitmap to the specified outputstream. 1037 * If this returns true, the bitmap can be reconstructed by passing a 1038 * corresponding inputstream to BitmapFactory.decodeStream(). Note: not 1039 * all Formats support all bitmap configs directly, so it is possible that 1040 * the returned bitmap from BitmapFactory could be in a different bitdepth, 1041 * and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque 1042 * pixels). 1043 * 1044 * @param format The format of the compressed image 1045 * @param quality Hint to the compressor, 0-100. 0 meaning compress for 1046 * small size, 100 meaning compress for max quality. Some 1047 * formats, like PNG which is lossless, will ignore the 1048 * quality setting 1049 * @param stream The outputstream to write the compressed data. 1050 * @return true if successfully compressed to the specified stream. 1051 */ 1052 public boolean compress(CompressFormat format, int quality, OutputStream stream) { 1053 checkRecycled("Can't compress a recycled bitmap"); 1054 // do explicit check before calling the native method 1055 if (stream == null) { 1056 throw new NullPointerException(); 1057 } 1058 if (quality < 0 || quality > 100) { 1059 throw new IllegalArgumentException("quality must be 0..100"); 1060 } 1061 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "Bitmap.compress"); 1062 boolean result = nativeCompress(mNativePtr, format.nativeInt, 1063 quality, stream, new byte[WORKING_COMPRESS_STORAGE]); 1064 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 1065 return result; 1066 } 1067 1068 /** 1069 * Returns true if the bitmap is marked as mutable (i.e. can be drawn into) 1070 */ 1071 public final boolean isMutable() { 1072 return mIsMutable; 1073 } 1074 1075 /** 1076 * <p>Indicates whether pixels stored in this bitmaps are stored pre-multiplied. 1077 * When a pixel is pre-multiplied, the RGB components have been multiplied by 1078 * the alpha component. For instance, if the original color is a 50% 1079 * translucent red <code>(128, 255, 0, 0)</code>, the pre-multiplied form is 1080 * <code>(128, 128, 0, 0)</code>.</p> 1081 * 1082 * <p>This method always returns false if {@link #getConfig()} is 1083 * {@link Bitmap.Config#RGB_565}.</p> 1084 * 1085 * <p>The return value is undefined if {@link #getConfig()} is 1086 * {@link Bitmap.Config#ALPHA_8}.</p> 1087 * 1088 * <p>This method only returns true if {@link #hasAlpha()} returns true. 1089 * A bitmap with no alpha channel can be used both as a pre-multiplied and 1090 * as a non pre-multiplied bitmap.</p> 1091 * 1092 * <p>Only pre-multiplied bitmaps may be drawn by the view system or 1093 * {@link Canvas}. If a non-pre-multiplied bitmap with an alpha channel is 1094 * drawn to a Canvas, a RuntimeException will be thrown.</p> 1095 * 1096 * @return true if the underlying pixels have been pre-multiplied, false 1097 * otherwise 1098 * 1099 * @see Bitmap#setPremultiplied(boolean) 1100 * @see BitmapFactory.Options#inPremultiplied 1101 */ 1102 public final boolean isPremultiplied() { 1103 if (mRecycled) { 1104 Log.w(TAG, "Called isPremultiplied() on a recycle()'d bitmap! This is undefined behavior!"); 1105 } 1106 return nativeIsPremultiplied(mNativePtr); 1107 } 1108 1109 /** 1110 * Sets whether the bitmap should treat its data as pre-multiplied. 1111 * 1112 * <p>Bitmaps are always treated as pre-multiplied by the view system and 1113 * {@link Canvas} for performance reasons. Storing un-pre-multiplied data in 1114 * a Bitmap (through {@link #setPixel}, {@link #setPixels}, or {@link 1115 * BitmapFactory.Options#inPremultiplied BitmapFactory.Options.inPremultiplied}) 1116 * can lead to incorrect blending if drawn by the framework.</p> 1117 * 1118 * <p>This method will not affect the behavior of a bitmap without an alpha 1119 * channel, or if {@link #hasAlpha()} returns false.</p> 1120 * 1121 * <p>Calling {@link #createBitmap} or {@link #createScaledBitmap} with a source 1122 * Bitmap whose colors are not pre-multiplied may result in a RuntimeException, 1123 * since those functions require drawing the source, which is not supported for 1124 * un-pre-multiplied Bitmaps.</p> 1125 * 1126 * @see Bitmap#isPremultiplied() 1127 * @see BitmapFactory.Options#inPremultiplied 1128 */ 1129 public final void setPremultiplied(boolean premultiplied) { 1130 checkRecycled("setPremultiplied called on a recycled bitmap"); 1131 mRequestPremultiplied = premultiplied; 1132 nativeSetPremultiplied(mNativePtr, premultiplied); 1133 } 1134 1135 /** Returns the bitmap's width */ 1136 public final int getWidth() { 1137 if (mRecycled) { 1138 Log.w(TAG, "Called getWidth() on a recycle()'d bitmap! This is undefined behavior!"); 1139 } 1140 return mWidth; 1141 } 1142 1143 /** Returns the bitmap's height */ 1144 public final int getHeight() { 1145 if (mRecycled) { 1146 Log.w(TAG, "Called getHeight() on a recycle()'d bitmap! This is undefined behavior!"); 1147 } 1148 return mHeight; 1149 } 1150 1151 /** 1152 * Convenience for calling {@link #getScaledWidth(int)} with the target 1153 * density of the given {@link Canvas}. 1154 */ 1155 public int getScaledWidth(Canvas canvas) { 1156 return scaleFromDensity(getWidth(), mDensity, canvas.mDensity); 1157 } 1158 1159 /** 1160 * Convenience for calling {@link #getScaledHeight(int)} with the target 1161 * density of the given {@link Canvas}. 1162 */ 1163 public int getScaledHeight(Canvas canvas) { 1164 return scaleFromDensity(getHeight(), mDensity, canvas.mDensity); 1165 } 1166 1167 /** 1168 * Convenience for calling {@link #getScaledWidth(int)} with the target 1169 * density of the given {@link DisplayMetrics}. 1170 */ 1171 public int getScaledWidth(DisplayMetrics metrics) { 1172 return scaleFromDensity(getWidth(), mDensity, metrics.densityDpi); 1173 } 1174 1175 /** 1176 * Convenience for calling {@link #getScaledHeight(int)} with the target 1177 * density of the given {@link DisplayMetrics}. 1178 */ 1179 public int getScaledHeight(DisplayMetrics metrics) { 1180 return scaleFromDensity(getHeight(), mDensity, metrics.densityDpi); 1181 } 1182 1183 /** 1184 * Convenience method that returns the width of this bitmap divided 1185 * by the density scale factor. 1186 * 1187 * @param targetDensity The density of the target canvas of the bitmap. 1188 * @return The scaled width of this bitmap, according to the density scale factor. 1189 */ 1190 public int getScaledWidth(int targetDensity) { 1191 return scaleFromDensity(getWidth(), mDensity, targetDensity); 1192 } 1193 1194 /** 1195 * Convenience method that returns the height of this bitmap divided 1196 * by the density scale factor. 1197 * 1198 * @param targetDensity The density of the target canvas of the bitmap. 1199 * @return The scaled height of this bitmap, according to the density scale factor. 1200 */ 1201 public int getScaledHeight(int targetDensity) { 1202 return scaleFromDensity(getHeight(), mDensity, targetDensity); 1203 } 1204 1205 /** 1206 * @hide 1207 */ 1208 static public int scaleFromDensity(int size, int sdensity, int tdensity) { 1209 if (sdensity == DENSITY_NONE || tdensity == DENSITY_NONE || sdensity == tdensity) { 1210 return size; 1211 } 1212 1213 // Scale by tdensity / sdensity, rounding up. 1214 return ((size * tdensity) + (sdensity >> 1)) / sdensity; 1215 } 1216 1217 /** 1218 * Return the number of bytes between rows in the bitmap's pixels. Note that 1219 * this refers to the pixels as stored natively by the bitmap. If you call 1220 * getPixels() or setPixels(), then the pixels are uniformly treated as 1221 * 32bit values, packed according to the Color class. 1222 * 1223 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, this method 1224 * should not be used to calculate the memory usage of the bitmap. Instead, 1225 * see {@link #getAllocationByteCount()}. 1226 * 1227 * @return number of bytes between rows of the native bitmap pixels. 1228 */ 1229 public final int getRowBytes() { 1230 if (mRecycled) { 1231 Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!"); 1232 } 1233 return nativeRowBytes(mNativePtr); 1234 } 1235 1236 /** 1237 * Returns the minimum number of bytes that can be used to store this bitmap's pixels. 1238 * 1239 * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can 1240 * no longer be used to determine memory usage of a bitmap. See {@link 1241 * #getAllocationByteCount()}.</p> 1242 */ 1243 public final int getByteCount() { 1244 if (mRecycled) { 1245 Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! " 1246 + "This is undefined behavior!"); 1247 return 0; 1248 } 1249 // int result permits bitmaps up to 46,340 x 46,340 1250 return getRowBytes() * getHeight(); 1251 } 1252 1253 /** 1254 * Returns the size of the allocated memory used to store this bitmap's pixels. 1255 * 1256 * <p>This can be larger than the result of {@link #getByteCount()} if a bitmap is reused to 1257 * decode other bitmaps of smaller size, or by manual reconfiguration. See {@link 1258 * #reconfigure(int, int, Config)}, {@link #setWidth(int)}, {@link #setHeight(int)}, {@link 1259 * #setConfig(Bitmap.Config)}, and {@link BitmapFactory.Options#inBitmap 1260 * BitmapFactory.Options.inBitmap}. If a bitmap is not modified in this way, this value will be 1261 * the same as that returned by {@link #getByteCount()}.</p> 1262 * 1263 * <p>This value will not change over the lifetime of a Bitmap.</p> 1264 * 1265 * @see #reconfigure(int, int, Config) 1266 */ 1267 public final int getAllocationByteCount() { 1268 if (mRecycled) { 1269 Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! " 1270 + "This is undefined behavior!"); 1271 return 0; 1272 } 1273 return nativeGetAllocationByteCount(mNativePtr); 1274 } 1275 1276 /** 1277 * If the bitmap's internal config is in one of the public formats, return 1278 * that config, otherwise return null. 1279 */ 1280 public final Config getConfig() { 1281 if (mRecycled) { 1282 Log.w(TAG, "Called getConfig() on a recycle()'d bitmap! This is undefined behavior!"); 1283 } 1284 return Config.nativeToConfig(nativeConfig(mNativePtr)); 1285 } 1286 1287 /** Returns true if the bitmap's config supports per-pixel alpha, and 1288 * if the pixels may contain non-opaque alpha values. For some configs, 1289 * this is always false (e.g. RGB_565), since they do not support per-pixel 1290 * alpha. However, for configs that do, the bitmap may be flagged to be 1291 * known that all of its pixels are opaque. In this case hasAlpha() will 1292 * also return false. If a config such as ARGB_8888 is not so flagged, 1293 * it will return true by default. 1294 */ 1295 public final boolean hasAlpha() { 1296 if (mRecycled) { 1297 Log.w(TAG, "Called hasAlpha() on a recycle()'d bitmap! This is undefined behavior!"); 1298 } 1299 return nativeHasAlpha(mNativePtr); 1300 } 1301 1302 /** 1303 * Tell the bitmap if all of the pixels are known to be opaque (false) 1304 * or if some of the pixels may contain non-opaque alpha values (true). 1305 * Note, for some configs (e.g. RGB_565) this call is ignored, since it 1306 * does not support per-pixel alpha values. 1307 * 1308 * This is meant as a drawing hint, as in some cases a bitmap that is known 1309 * to be opaque can take a faster drawing case than one that may have 1310 * non-opaque per-pixel alpha values. 1311 */ 1312 public void setHasAlpha(boolean hasAlpha) { 1313 checkRecycled("setHasAlpha called on a recycled bitmap"); 1314 nativeSetHasAlpha(mNativePtr, hasAlpha, mRequestPremultiplied); 1315 } 1316 1317 /** 1318 * Indicates whether the renderer responsible for drawing this 1319 * bitmap should attempt to use mipmaps when this bitmap is drawn 1320 * scaled down. 1321 * 1322 * If you know that you are going to draw this bitmap at less than 1323 * 50% of its original size, you may be able to obtain a higher 1324 * quality 1325 * 1326 * This property is only a suggestion that can be ignored by the 1327 * renderer. It is not guaranteed to have any effect. 1328 * 1329 * @return true if the renderer should attempt to use mipmaps, 1330 * false otherwise 1331 * 1332 * @see #setHasMipMap(boolean) 1333 */ 1334 public final boolean hasMipMap() { 1335 if (mRecycled) { 1336 Log.w(TAG, "Called hasMipMap() on a recycle()'d bitmap! This is undefined behavior!"); 1337 } 1338 return nativeHasMipMap(mNativePtr); 1339 } 1340 1341 /** 1342 * Set a hint for the renderer responsible for drawing this bitmap 1343 * indicating that it should attempt to use mipmaps when this bitmap 1344 * is drawn scaled down. 1345 * 1346 * If you know that you are going to draw this bitmap at less than 1347 * 50% of its original size, you may be able to obtain a higher 1348 * quality by turning this property on. 1349 * 1350 * Note that if the renderer respects this hint it might have to 1351 * allocate extra memory to hold the mipmap levels for this bitmap. 1352 * 1353 * This property is only a suggestion that can be ignored by the 1354 * renderer. It is not guaranteed to have any effect. 1355 * 1356 * @param hasMipMap indicates whether the renderer should attempt 1357 * to use mipmaps 1358 * 1359 * @see #hasMipMap() 1360 */ 1361 public final void setHasMipMap(boolean hasMipMap) { 1362 checkRecycled("setHasMipMap called on a recycled bitmap"); 1363 nativeSetHasMipMap(mNativePtr, hasMipMap); 1364 } 1365 1366 /** 1367 * Fills the bitmap's pixels with the specified {@link Color}. 1368 * 1369 * @throws IllegalStateException if the bitmap is not mutable. 1370 */ 1371 public void eraseColor(@ColorInt int c) { 1372 checkRecycled("Can't erase a recycled bitmap"); 1373 if (!isMutable()) { 1374 throw new IllegalStateException("cannot erase immutable bitmaps"); 1375 } 1376 nativeErase(mNativePtr, c); 1377 } 1378 1379 /** 1380 * Returns the {@link Color} at the specified location. Throws an exception 1381 * if x or y are out of bounds (negative or >= to the width or height 1382 * respectively). The returned color is a non-premultiplied ARGB value. 1383 * 1384 * @param x The x coordinate (0...width-1) of the pixel to return 1385 * @param y The y coordinate (0...height-1) of the pixel to return 1386 * @return The argb {@link Color} at the specified coordinate 1387 * @throws IllegalArgumentException if x, y exceed the bitmap's bounds 1388 */ 1389 @ColorInt 1390 public int getPixel(int x, int y) { 1391 checkRecycled("Can't call getPixel() on a recycled bitmap"); 1392 checkPixelAccess(x, y); 1393 return nativeGetPixel(mNativePtr, x, y); 1394 } 1395 1396 /** 1397 * Returns in pixels[] a copy of the data in the bitmap. Each value is 1398 * a packed int representing a {@link Color}. The stride parameter allows 1399 * the caller to allow for gaps in the returned pixels array between 1400 * rows. For normal packed results, just pass width for the stride value. 1401 * The returned colors are non-premultiplied ARGB values. 1402 * 1403 * @param pixels The array to receive the bitmap's colors 1404 * @param offset The first index to write into pixels[] 1405 * @param stride The number of entries in pixels[] to skip between 1406 * rows (must be >= bitmap's width). Can be negative. 1407 * @param x The x coordinate of the first pixel to read from 1408 * the bitmap 1409 * @param y The y coordinate of the first pixel to read from 1410 * the bitmap 1411 * @param width The number of pixels to read from each row 1412 * @param height The number of rows to read 1413 * 1414 * @throws IllegalArgumentException if x, y, width, height exceed the 1415 * bounds of the bitmap, or if abs(stride) < width. 1416 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1417 * to receive the specified number of pixels. 1418 */ 1419 public void getPixels(@ColorInt int[] pixels, int offset, int stride, 1420 int x, int y, int width, int height) { 1421 checkRecycled("Can't call getPixels() on a recycled bitmap"); 1422 if (width == 0 || height == 0) { 1423 return; // nothing to do 1424 } 1425 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1426 nativeGetPixels(mNativePtr, pixels, offset, stride, 1427 x, y, width, height); 1428 } 1429 1430 /** 1431 * Shared code to check for illegal arguments passed to getPixel() 1432 * or setPixel() 1433 * 1434 * @param x x coordinate of the pixel 1435 * @param y y coordinate of the pixel 1436 */ 1437 private void checkPixelAccess(int x, int y) { 1438 checkXYSign(x, y); 1439 if (x >= getWidth()) { 1440 throw new IllegalArgumentException("x must be < bitmap.width()"); 1441 } 1442 if (y >= getHeight()) { 1443 throw new IllegalArgumentException("y must be < bitmap.height()"); 1444 } 1445 } 1446 1447 /** 1448 * Shared code to check for illegal arguments passed to getPixels() 1449 * or setPixels() 1450 * 1451 * @param x left edge of the area of pixels to access 1452 * @param y top edge of the area of pixels to access 1453 * @param width width of the area of pixels to access 1454 * @param height height of the area of pixels to access 1455 * @param offset offset into pixels[] array 1456 * @param stride number of elements in pixels[] between each logical row 1457 * @param pixels array to hold the area of pixels being accessed 1458 */ 1459 private void checkPixelsAccess(int x, int y, int width, int height, 1460 int offset, int stride, int pixels[]) { 1461 checkXYSign(x, y); 1462 if (width < 0) { 1463 throw new IllegalArgumentException("width must be >= 0"); 1464 } 1465 if (height < 0) { 1466 throw new IllegalArgumentException("height must be >= 0"); 1467 } 1468 if (x + width > getWidth()) { 1469 throw new IllegalArgumentException( 1470 "x + width must be <= bitmap.width()"); 1471 } 1472 if (y + height > getHeight()) { 1473 throw new IllegalArgumentException( 1474 "y + height must be <= bitmap.height()"); 1475 } 1476 if (Math.abs(stride) < width) { 1477 throw new IllegalArgumentException("abs(stride) must be >= width"); 1478 } 1479 int lastScanline = offset + (height - 1) * stride; 1480 int length = pixels.length; 1481 if (offset < 0 || (offset + width > length) 1482 || lastScanline < 0 1483 || (lastScanline + width > length)) { 1484 throw new ArrayIndexOutOfBoundsException(); 1485 } 1486 } 1487 1488 /** 1489 * <p>Write the specified {@link Color} into the bitmap (assuming it is 1490 * mutable) at the x,y coordinate. The color must be a 1491 * non-premultiplied ARGB value.</p> 1492 * 1493 * @param x The x coordinate of the pixel to replace (0...width-1) 1494 * @param y The y coordinate of the pixel to replace (0...height-1) 1495 * @param color The ARGB color to write into the bitmap 1496 * 1497 * @throws IllegalStateException if the bitmap is not mutable 1498 * @throws IllegalArgumentException if x, y are outside of the bitmap's 1499 * bounds. 1500 */ 1501 public void setPixel(int x, int y, @ColorInt int color) { 1502 checkRecycled("Can't call setPixel() on a recycled bitmap"); 1503 if (!isMutable()) { 1504 throw new IllegalStateException(); 1505 } 1506 checkPixelAccess(x, y); 1507 nativeSetPixel(mNativePtr, x, y, color); 1508 } 1509 1510 /** 1511 * <p>Replace pixels in the bitmap with the colors in the array. Each element 1512 * in the array is a packed int prepresenting a non-premultiplied ARGB 1513 * {@link Color}.</p> 1514 * 1515 * @param pixels The colors to write to the bitmap 1516 * @param offset The index of the first color to read from pixels[] 1517 * @param stride The number of colors in pixels[] to skip between rows. 1518 * Normally this value will be the same as the width of 1519 * the bitmap, but it can be larger (or negative). 1520 * @param x The x coordinate of the first pixel to write to in 1521 * the bitmap. 1522 * @param y The y coordinate of the first pixel to write to in 1523 * the bitmap. 1524 * @param width The number of colors to copy from pixels[] per row 1525 * @param height The number of rows to write to the bitmap 1526 * 1527 * @throws IllegalStateException if the bitmap is not mutable 1528 * @throws IllegalArgumentException if x, y, width, height are outside of 1529 * the bitmap's bounds. 1530 * @throws ArrayIndexOutOfBoundsException if the pixels array is too small 1531 * to receive the specified number of pixels. 1532 */ 1533 public void setPixels(@ColorInt int[] pixels, int offset, int stride, 1534 int x, int y, int width, int height) { 1535 checkRecycled("Can't call setPixels() on a recycled bitmap"); 1536 if (!isMutable()) { 1537 throw new IllegalStateException(); 1538 } 1539 if (width == 0 || height == 0) { 1540 return; // nothing to do 1541 } 1542 checkPixelsAccess(x, y, width, height, offset, stride, pixels); 1543 nativeSetPixels(mNativePtr, pixels, offset, stride, 1544 x, y, width, height); 1545 } 1546 1547 public static final Parcelable.Creator<Bitmap> CREATOR 1548 = new Parcelable.Creator<Bitmap>() { 1549 /** 1550 * Rebuilds a bitmap previously stored with writeToParcel(). 1551 * 1552 * @param p Parcel object to read the bitmap from 1553 * @return a new bitmap created from the data in the parcel 1554 */ 1555 public Bitmap createFromParcel(Parcel p) { 1556 Bitmap bm = nativeCreateFromParcel(p); 1557 if (bm == null) { 1558 throw new RuntimeException("Failed to unparcel Bitmap"); 1559 } 1560 return bm; 1561 } 1562 public Bitmap[] newArray(int size) { 1563 return new Bitmap[size]; 1564 } 1565 }; 1566 1567 /** 1568 * No special parcel contents. 1569 */ 1570 public int describeContents() { 1571 return 0; 1572 } 1573 1574 /** 1575 * Write the bitmap and its pixels to the parcel. The bitmap can be 1576 * rebuilt from the parcel by calling CREATOR.createFromParcel(). 1577 * @param p Parcel object to write the bitmap data into 1578 */ 1579 public void writeToParcel(Parcel p, int flags) { 1580 checkRecycled("Can't parcel a recycled bitmap"); 1581 if (!nativeWriteToParcel(mNativePtr, mIsMutable, mDensity, p)) { 1582 throw new RuntimeException("native writeToParcel failed"); 1583 } 1584 } 1585 1586 /** 1587 * Returns a new bitmap that captures the alpha values of the original. 1588 * This may be drawn with Canvas.drawBitmap(), where the color(s) will be 1589 * taken from the paint that is passed to the draw call. 1590 * 1591 * @return new bitmap containing the alpha channel of the original bitmap. 1592 */ 1593 @CheckResult 1594 public Bitmap extractAlpha() { 1595 return extractAlpha(null, null); 1596 } 1597 1598 /** 1599 * Returns a new bitmap that captures the alpha values of the original. 1600 * These values may be affected by the optional Paint parameter, which 1601 * can contain its own alpha, and may also contain a MaskFilter which 1602 * could change the actual dimensions of the resulting bitmap (e.g. 1603 * a blur maskfilter might enlarge the resulting bitmap). If offsetXY 1604 * is not null, it returns the amount to offset the returned bitmap so 1605 * that it will logically align with the original. For example, if the 1606 * paint contains a blur of radius 2, then offsetXY[] would contains 1607 * -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then 1608 * drawing the original would result in the blur visually aligning with 1609 * the original. 1610 * 1611 * <p>The initial density of the returned bitmap is the same as the original's. 1612 * 1613 * @param paint Optional paint used to modify the alpha values in the 1614 * resulting bitmap. Pass null for default behavior. 1615 * @param offsetXY Optional array that returns the X (index 0) and Y 1616 * (index 1) offset needed to position the returned bitmap 1617 * so that it visually lines up with the original. 1618 * @return new bitmap containing the (optionally modified by paint) alpha 1619 * channel of the original bitmap. This may be drawn with 1620 * Canvas.drawBitmap(), where the color(s) will be taken from the 1621 * paint that is passed to the draw call. 1622 */ 1623 @CheckResult 1624 public Bitmap extractAlpha(Paint paint, int[] offsetXY) { 1625 checkRecycled("Can't extractAlpha on a recycled bitmap"); 1626 long nativePaint = paint != null ? paint.getNativeInstance() : 0; 1627 Bitmap bm = nativeExtractAlpha(mNativePtr, nativePaint, offsetXY); 1628 if (bm == null) { 1629 throw new RuntimeException("Failed to extractAlpha on Bitmap"); 1630 } 1631 bm.mDensity = mDensity; 1632 return bm; 1633 } 1634 1635 /** 1636 * Given another bitmap, return true if it has the same dimensions, config, 1637 * and pixel data as this bitmap. If any of those differ, return false. 1638 * If other is null, return false. 1639 */ 1640 public boolean sameAs(Bitmap other) { 1641 checkRecycled("Can't call sameAs on a recycled bitmap!"); 1642 if (this == other) return true; 1643 if (other == null) return false; 1644 if (other.isRecycled()) { 1645 throw new IllegalArgumentException("Can't compare to a recycled bitmap!"); 1646 } 1647 return nativeSameAs(mNativePtr, other.mNativePtr); 1648 } 1649 1650 /** 1651 * Rebuilds any caches associated with the bitmap that are used for 1652 * drawing it. In the case of purgeable bitmaps, this call will attempt to 1653 * ensure that the pixels have been decoded. 1654 * If this is called on more than one bitmap in sequence, the priority is 1655 * given in LRU order (i.e. the last bitmap called will be given highest 1656 * priority). 1657 * 1658 * For bitmaps with no associated caches, this call is effectively a no-op, 1659 * and therefore is harmless. 1660 */ 1661 public void prepareToDraw() { 1662 checkRecycled("Can't prepareToDraw on a recycled bitmap!"); 1663 // Kick off an update/upload of the bitmap outside of the normal 1664 // draw path. 1665 nativePrepareToDraw(mNativePtr); 1666 } 1667 1668 //////////// native methods 1669 1670 private static native Bitmap nativeCreate(int[] colors, int offset, 1671 int stride, int width, int height, 1672 int nativeConfig, boolean mutable); 1673 private static native Bitmap nativeCopy(long nativeSrcBitmap, int nativeConfig, 1674 boolean isMutable); 1675 private static native Bitmap nativeCopyAshmem(long nativeSrcBitmap); 1676 private static native Bitmap nativeCopyAshmemConfig(long nativeSrcBitmap, int nativeConfig); 1677 private static native long nativeGetNativeFinalizer(); 1678 private static native boolean nativeRecycle(long nativeBitmap); 1679 private static native void nativeReconfigure(long nativeBitmap, int width, int height, 1680 int config, boolean isPremultiplied); 1681 1682 private static native boolean nativeCompress(long nativeBitmap, int format, 1683 int quality, OutputStream stream, 1684 byte[] tempStorage); 1685 private static native void nativeErase(long nativeBitmap, int color); 1686 private static native int nativeRowBytes(long nativeBitmap); 1687 private static native int nativeConfig(long nativeBitmap); 1688 1689 private static native int nativeGetPixel(long nativeBitmap, int x, int y); 1690 private static native void nativeGetPixels(long nativeBitmap, int[] pixels, 1691 int offset, int stride, int x, int y, 1692 int width, int height); 1693 1694 private static native void nativeSetPixel(long nativeBitmap, int x, int y, int color); 1695 private static native void nativeSetPixels(long nativeBitmap, int[] colors, 1696 int offset, int stride, int x, int y, 1697 int width, int height); 1698 private static native void nativeCopyPixelsToBuffer(long nativeBitmap, 1699 Buffer dst); 1700 private static native void nativeCopyPixelsFromBuffer(long nativeBitmap, Buffer src); 1701 private static native int nativeGenerationId(long nativeBitmap); 1702 1703 private static native Bitmap nativeCreateFromParcel(Parcel p); 1704 // returns true on success 1705 private static native boolean nativeWriteToParcel(long nativeBitmap, 1706 boolean isMutable, 1707 int density, 1708 Parcel p); 1709 // returns a new bitmap built from the native bitmap's alpha, and the paint 1710 private static native Bitmap nativeExtractAlpha(long nativeBitmap, 1711 long nativePaint, 1712 int[] offsetXY); 1713 1714 private static native boolean nativeHasAlpha(long nativeBitmap); 1715 private static native boolean nativeIsPremultiplied(long nativeBitmap); 1716 private static native void nativeSetPremultiplied(long nativeBitmap, 1717 boolean isPremul); 1718 private static native void nativeSetHasAlpha(long nativeBitmap, 1719 boolean hasAlpha, 1720 boolean requestPremul); 1721 private static native boolean nativeHasMipMap(long nativeBitmap); 1722 private static native void nativeSetHasMipMap(long nativeBitmap, boolean hasMipMap); 1723 private static native boolean nativeSameAs(long nativeBitmap0, long nativeBitmap1); 1724 private static native void nativePrepareToDraw(long nativeBitmap); 1725 private static native int nativeGetAllocationByteCount(long nativeBitmap); 1726} 1727