2 * Copyright 2006 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef SkBitmap_DEFINED
9 #define SkBitmap_DEFINED
12 #include "SkColorTable.h"
13 #include "SkImageInfo.h"
21 class SkPixelRefFactory;
29 The SkBitmap class specifies a raster bitmap. A bitmap has an integer width
30 and height, and a format (config), and a pointer to the actual pixels.
31 Bitmaps can be drawn into a SkCanvas, but they are also used to specify the
32 target of a SkCanvas' drawing operations.
33 A const SkBitmap exposes getAddr(), which lets a caller write its pixels;
34 the constness is considered to apply to the bitmap's configuration, not
37 class SK_API SkBitmap {
39 class SK_API Allocator;
42 kNo_Config, //!< bitmap has not been configured
43 kA8_Config, //!< 8-bits per pixel, with only alpha specified (0 is transparent, 0xFF is opaque)
44 kIndex8_Config, //!< 8-bits per pixel, using SkColorTable to specify the colors
45 kRGB_565_Config, //!< 16-bits per pixel, (see SkColorPriv.h for packing)
46 kARGB_4444_Config, //!< 16-bits per pixel, (see SkColorPriv.h for packing)
47 kARGB_8888_Config, //!< 32-bits per pixel, (see SkColorPriv.h for packing)
50 // do not add this to the Config enum, otherwise the compiler will let us
51 // pass this as a valid parameter for Config.
53 kConfigCount = kARGB_8888_Config + 1
57 * Default construct creates a bitmap with zero width and height, and no pixels.
58 * Its config is set to kNo_Config.
63 * Copy the settings from the src into this bitmap. If the src has pixels
64 * allocated, they will be shared, not copied, so that the two bitmaps will
65 * reference the same memory for the pixels. If a deep copy is needed,
66 * where the new bitmap has its own separate copy of the pixels, use
69 SkBitmap(const SkBitmap& src);
73 /** Copies the src bitmap into this bitmap. Ownership of the src bitmap's pixels remains
76 SkBitmap& operator=(const SkBitmap& src);
77 /** Swap the fields of the two bitmaps. This routine is guaranteed to never fail or throw.
79 // This method is not exported to java.
80 void swap(SkBitmap& other);
82 ///////////////////////////////////////////////////////////////////////////
84 const SkImageInfo& info() const { return fInfo; }
86 int width() const { return fInfo.fWidth; }
87 int height() const { return fInfo.fHeight; }
88 SkColorType colorType() const { return fInfo.fColorType; }
89 SkAlphaType alphaType() const { return fInfo.fAlphaType; }
91 /** Return the number of bytes per pixel based on the config. If the config
92 does not have at least 1 byte per (e.g. kA1_Config) then 0 is returned.
94 int bytesPerPixel() const { return fInfo.bytesPerPixel(); }
96 /** Return the rowbytes expressed as a number of pixels (like width and
97 height). Note, for 1-byte per pixel configs like kA8_Config, this will
98 return the same as rowBytes(). Is undefined for configs that are less
99 than 1-byte per pixel (e.g. kA1_Config)
101 int rowBytesAsPixels() const {
102 return fRowBytes >> this->shiftPerPixel();
105 /** Return the shift amount per pixel (i.e. 0 for 1-byte per pixel, 1 for
106 2-bytes per pixel configs, 2 for 4-bytes per pixel configs). Return 0
107 for configs that are not at least 1-byte per pixel (e.g. kA1_Config
110 int shiftPerPixel() const { return this->bytesPerPixel() >> 1; }
112 ///////////////////////////////////////////////////////////////////////////
114 /** Return true iff the bitmap has empty dimensions.
115 * Hey! Before you use this, see if you really want to know drawsNothing() instead.
117 bool empty() const { return fInfo.isEmpty(); }
119 /** Return true iff the bitmap has no pixelref. Note: this can return true even if the
120 * dimensions of the bitmap are > 0 (see empty()).
121 * Hey! Before you use this, see if you really want to know drawsNothing() instead.
123 bool isNull() const { return NULL == fPixelRef; }
125 /** Return true iff drawing this bitmap has no effect.
127 bool drawsNothing() const { return this->empty() || this->isNull(); }
129 /** Return the config for the bitmap. */
130 Config config() const;
132 SK_ATTR_DEPRECATED("use config()")
133 Config getConfig() const { return this->config(); }
135 /** Return the number of bytes between subsequent rows of the bitmap. */
136 size_t rowBytes() const { return fRowBytes; }
139 * Set the bitmap's alphaType, returning true on success. If false is
140 * returned, then the specified new alphaType is incompatible with the
141 * Config, and the current alphaType is unchanged.
143 * Note: this changes the alphatype for the underlying pixels, which means
144 * that all bitmaps that might be sharing (subsets of) the pixels will
147 bool setAlphaType(SkAlphaType);
149 /** Return the address of the pixels for this SkBitmap.
151 void* getPixels() const { return fPixels; }
153 /** Return the byte size of the pixels, based on the height and rowBytes.
154 Note this truncates the result to 32bits. Call getSize64() to detect
155 if the real size exceeds 32bits.
157 size_t getSize() const { return fInfo.fHeight * fRowBytes; }
159 /** Return the number of bytes from the pointer returned by getPixels()
160 to the end of the allocated space in the buffer. Required in
161 cases where extractSubset has been called.
163 size_t getSafeSize() const { return fInfo.getSafeSize(fRowBytes); }
166 * Return the full size of the bitmap, in bytes.
168 int64_t computeSize64() const {
169 return sk_64_mul(fInfo.fHeight, fRowBytes);
173 * Return the number of bytes from the pointer returned by getPixels()
174 * to the end of the allocated space in the buffer. This may be smaller
175 * than computeSize64() if there is any rowbytes padding beyond the width.
177 int64_t computeSafeSize64() const {
178 return fInfo.getSafeSize64(fRowBytes);
181 /** Returns true if this bitmap is marked as immutable, meaning that the
182 contents of its pixels will not change for the lifetime of the bitmap.
184 bool isImmutable() const;
186 /** Marks this bitmap as immutable, meaning that the contents of its
187 pixels will not change for the lifetime of the bitmap and of the
188 underlying pixelref. This state can be set, but it cannot be
189 cleared once it is set. This state propagates to all other bitmaps
190 that share the same pixelref.
194 /** Returns true if the bitmap is opaque (has no translucent/transparent pixels).
196 bool isOpaque() const {
197 return SkAlphaTypeIsOpaque(this->alphaType());
200 /** Returns true if the bitmap is volatile (i.e. should not be cached by devices.)
202 bool isVolatile() const;
204 /** Specify whether this bitmap is volatile. Bitmaps are not volatile by
205 default. Temporary bitmaps that are discarded after use should be
206 marked as volatile. This provides a hint to the device that the bitmap
207 should not be cached. Providing this hint when appropriate can
208 improve performance by avoiding unnecessary overhead and resource
209 consumption on the device.
211 void setIsVolatile(bool);
213 /** Reset the bitmap to its initial state (see default constructor). If we are a (shared)
214 owner of the pixels, that ownership is decremented.
218 /** Given a config and a width, this computes the optimal rowBytes value. This is called automatically
219 if you pass 0 for rowBytes to setConfig().
221 static size_t ComputeRowBytes(Config c, int width);
223 /** Return the bytes-per-pixel for the specified config. If the config is
224 not at least 1-byte per pixel, return 0, including for kNo_Config.
226 static int ComputeBytesPerPixel(Config c);
228 /** Return the shift-per-pixel for the specified config. If the config is
229 not at least 1-byte per pixel, return 0, including for kNo_Config.
231 static int ComputeShiftPerPixel(Config c) {
232 return ComputeBytesPerPixel(c) >> 1;
235 static int64_t ComputeSize64(Config, int width, int height);
236 static size_t ComputeSize(Config, int width, int height);
239 * This will brute-force return true if all of the pixels in the bitmap
240 * are opaque. If it fails to read the pixels, or encounters an error,
241 * it will return false.
243 * Since this can be an expensive operation, the bitmap stores a flag for
244 * this (isOpaque). Only call this if you need to compute this value from
247 static bool ComputeIsOpaque(const SkBitmap&);
250 * Return the bitmap's bounds [0, 0, width, height] as an SkRect
252 void getBounds(SkRect* bounds) const;
253 void getBounds(SkIRect* bounds) const;
255 /** Set the bitmap's config and dimensions. If rowBytes is 0, then
256 ComputeRowBytes() is called to compute the optimal value. This resets
257 any pixel/colortable ownership, just like reset().
259 bool setConfig(Config, int width, int height, size_t rowBytes, SkAlphaType);
261 bool setConfig(Config config, int width, int height, size_t rowBytes = 0) {
262 return this->setConfig(config, width, height, rowBytes,
263 kPremul_SkAlphaType);
266 bool setConfig(const SkImageInfo& info, size_t rowBytes = 0);
269 * Allocate a pixelref to match the specified image info. If the Factory
270 * is non-null, call it to allcoate the pixelref. If the ImageInfo requires
271 * a colortable, then ColorTable must be non-null, and will be ref'd.
272 * On failure, the bitmap will be set to empty and return false.
274 bool allocPixels(const SkImageInfo&, SkPixelRefFactory*, SkColorTable*);
277 * Allocate a pixelref to match the specified image info, using the default
279 * On success, the bitmap's pixels will be "locked", and return true.
280 * On failure, the bitmap will be set to empty and return false.
282 bool allocPixels(const SkImageInfo& info) {
283 return this->allocPixels(info, NULL, NULL);
287 * Legacy helper function, which creates an SkImageInfo from the specified
288 * config and then calls allocPixels(info).
290 bool allocConfigPixels(Config, int width, int height, bool isOpaque = false);
292 bool allocN32Pixels(int width, int height, bool isOpaque = false) {
293 SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);
295 info.fAlphaType = kOpaque_SkAlphaType;
297 return this->allocPixels(info);
301 * Install a pixelref that wraps the specified pixels and rowBytes, and
302 * optional ReleaseProc and context. When the pixels are no longer
303 * referenced, if ReleaseProc is not null, it will be called with the
304 * pixels and context as parameters.
305 * On failure, the bitmap will be set to empty and return false.
307 bool installPixels(const SkImageInfo&, void* pixels, size_t rowBytes,
308 void (*ReleaseProc)(void* addr, void* context),
312 * DEPRECATED: call info().
314 bool asImageInfo(SkImageInfo* info) const {
315 // compatibility: return false for kUnknown
316 if (kUnknown_SkColorType == this->colorType()) {
320 *info = this->info();
325 /** Use this to assign a new pixel address for an existing bitmap. This
326 will automatically release any pixelref previously installed. Only call
327 this if you are handling ownership/lifetime of the pixel memory.
329 If the bitmap retains a reference to the colortable (assuming it is
330 not null) it will take care of incrementing the reference count.
332 @param pixels Address for the pixels, managed by the caller.
333 @param ctable ColorTable (or null) that matches the specified pixels
335 void setPixels(void* p, SkColorTable* ctable = NULL);
337 /** Copies the bitmap's pixels to the location pointed at by dst and returns
338 true if possible, returns false otherwise.
340 In the case when the dstRowBytes matches the bitmap's rowBytes, the copy
341 may be made faster by copying over the dst's per-row padding (for all
342 rows but the last). By setting preserveDstPad to true the caller can
343 disable this optimization and ensure that pixels in the padding are not
346 Always returns false for RLE formats.
348 @param dst Location of destination buffer.
349 @param dstSize Size of destination buffer. Must be large enough to hold
350 pixels using indicated stride.
351 @param dstRowBytes Width of each line in the buffer. If 0, uses
352 bitmap's internal stride.
353 @param preserveDstPad Must we preserve padding in the dst
355 bool copyPixelsTo(void* const dst, size_t dstSize, size_t dstRowBytes = 0,
356 bool preserveDstPad = false) const;
358 /** Use the standard HeapAllocator to create the pixelref that manages the
359 pixel memory. It will be sized based on the current width/height/config.
360 If this is called multiple times, a new pixelref object will be created
363 If the bitmap retains a reference to the colortable (assuming it is
364 not null) it will take care of incrementing the reference count.
366 @param ctable ColorTable (or null) to use with the pixels that will
367 be allocated. Only used if config == Index8_Config
368 @return true if the allocation succeeds. If not the pixelref field of
369 the bitmap will be unchanged.
371 bool allocPixels(SkColorTable* ctable = NULL) {
372 return this->allocPixels(NULL, ctable);
375 /** Use the specified Allocator to create the pixelref that manages the
376 pixel memory. It will be sized based on the current width/height/config.
377 If this is called multiple times, a new pixelref object will be created
380 If the bitmap retains a reference to the colortable (assuming it is
381 not null) it will take care of incrementing the reference count.
383 @param allocator The Allocator to use to create a pixelref that can
384 manage the pixel memory for the current
385 width/height/config. If allocator is NULL, the standard
386 HeapAllocator will be used.
387 @param ctable ColorTable (or null) to use with the pixels that will
388 be allocated. Only used if config == Index8_Config.
389 If it is non-null and the config is not Index8, it will
391 @return true if the allocation succeeds. If not the pixelref field of
392 the bitmap will be unchanged.
394 bool allocPixels(Allocator* allocator, SkColorTable* ctable);
397 * Return the current pixelref object or NULL if there is none. This does
398 * not affect the refcount of the pixelref.
400 SkPixelRef* pixelRef() const { return fPixelRef; }
403 * A bitmap can reference a subset of a pixelref's pixels. That means the
404 * bitmap's width/height can be <= the dimensions of the pixelref. The
405 * pixelref origin is the x,y location within the pixelref's pixels for
406 * the bitmap's top/left corner. To be valid the following must be true:
408 * origin_x + bitmap_width <= pixelref_width
409 * origin_y + bitmap_height <= pixelref_height
411 * pixelRefOrigin() returns this origin, or (0,0) if there is no pixelRef.
413 SkIPoint pixelRefOrigin() const { return fPixelRefOrigin; }
416 * Assign a pixelref and origin to the bitmap. Pixelrefs are reference,
417 * so the existing one (if any) will be unref'd and the new one will be
418 * ref'd. (x,y) specify the offset within the pixelref's pixels for the
419 * top/left corner of the bitmap. For a bitmap that encompases the entire
420 * pixels of the pixelref, these will be (0,0).
422 SkPixelRef* setPixelRef(SkPixelRef* pr, int dx, int dy);
424 SkPixelRef* setPixelRef(SkPixelRef* pr, const SkIPoint& origin) {
425 return this->setPixelRef(pr, origin.fX, origin.fY);
428 SkPixelRef* setPixelRef(SkPixelRef* pr) {
429 return this->setPixelRef(pr, 0, 0);
432 /** Call this to ensure that the bitmap points to the current pixel address
433 in the pixelref. Balance it with a call to unlockPixels(). These calls
434 are harmless if there is no pixelref.
436 void lockPixels() const;
437 /** When you are finished access the pixel memory, call this to balance a
438 previous call to lockPixels(). This allows pixelrefs that implement
439 cached/deferred image decoding to know when there are active clients of
442 void unlockPixels() const;
445 * Some bitmaps can return a copy of their pixels for lockPixels(), but
446 * that copy, if modified, will not be pushed back. These bitmaps should
447 * not be used as targets for a raster device/canvas (since all pixels
448 * modifications will be lost when unlockPixels() is called.)
450 bool lockPixelsAreWritable() const;
452 /** Call this to be sure that the bitmap is valid enough to be drawn (i.e.
453 it has non-null pixels, and if required by its config, it has a
454 non-null colortable. Returns true if all of the above are met.
456 bool readyToDraw() const {
457 return this->getPixels() != NULL &&
458 (this->config() != kIndex8_Config || NULL != fColorTable);
461 /** Returns the pixelRef's texture, or NULL
463 GrTexture* getTexture() const;
465 /** Return the bitmap's colortable, if it uses one (i.e. colorType is
466 Index_8) and the pixels are locked.
467 Otherwise returns NULL. Does not affect the colortable's
470 SkColorTable* getColorTable() const { return fColorTable; }
472 /** Returns a non-zero, unique value corresponding to the pixels in our
473 pixelref. Each time the pixels are changed (and notifyPixelsChanged
474 is called), a different generation ID will be returned. Finally, if
475 their is no pixelRef then zero is returned.
477 uint32_t getGenerationID() const;
479 /** Call this if you have changed the contents of the pixels. This will in-
480 turn cause a different generation ID value to be returned from
483 void notifyPixelsChanged() const;
486 * Fill the entire bitmap with the specified color.
487 * If the bitmap's config does not support alpha (e.g. 565) then the alpha
488 * of the color is ignored (treated as opaque). If the config only supports
489 * alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
491 void eraseColor(SkColor c) const {
492 this->eraseARGB(SkColorGetA(c), SkColorGetR(c), SkColorGetG(c),
497 * Fill the entire bitmap with the specified color.
498 * If the bitmap's config does not support alpha (e.g. 565) then the alpha
499 * of the color is ignored (treated as opaque). If the config only supports
500 * alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
502 void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const;
504 SK_ATTR_DEPRECATED("use eraseARGB or eraseColor")
505 void eraseRGB(U8CPU r, U8CPU g, U8CPU b) const {
506 this->eraseARGB(0xFF, r, g, b);
510 * Fill the specified area of this bitmap with the specified color.
511 * If the bitmap's config does not support alpha (e.g. 565) then the alpha
512 * of the color is ignored (treated as opaque). If the config only supports
513 * alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
515 void eraseArea(const SkIRect& area, SkColor c) const;
517 /** Scroll (a subset of) the contents of this bitmap by dx/dy. If there are
518 no pixels allocated (i.e. getPixels() returns null) the method will
519 still update the inval region (if present). If the bitmap is immutable,
520 do nothing and return false.
522 @param subset The subset of the bitmap to scroll/move. To scroll the
523 entire contents, specify [0, 0, width, height] or just
525 @param dx The amount to scroll in X
526 @param dy The amount to scroll in Y
527 @param inval Optional (may be null). Returns the area of the bitmap that
528 was scrolled away. E.g. if dx = dy = 0, then inval would
529 be set to empty. If dx >= width or dy >= height, then
530 inval would be set to the entire bounds of the bitmap.
531 @return true if the scroll was doable. Will return false if the bitmap
532 uses an unsupported config for scrolling (only kA8,
533 kIndex8, kRGB_565, kARGB_4444, kARGB_8888 are supported).
534 If no pixels are present (i.e. getPixels() returns false)
535 inval will still be updated, and true will be returned.
537 bool scrollRect(const SkIRect* subset, int dx, int dy,
538 SkRegion* inval = NULL) const;
541 * Return the SkColor of the specified pixel. In most cases this will
542 * require un-premultiplying the color. Alpha only configs (A1 and A8)
543 * return black with the appropriate alpha set. The value is undefined
544 * for kNone_Config or if x or y are out of bounds, or if the bitmap
545 * does not have any pixels (or has not be locked with lockPixels()).
547 SkColor getColor(int x, int y) const;
549 /** Returns the address of the specified pixel. This performs a runtime
550 check to know the size of the pixels, and will return the same answer
551 as the corresponding size-specific method (e.g. getAddr16). Since the
552 check happens at runtime, it is much slower than using a size-specific
553 version. Unlike the size-specific methods, this routine also checks if
554 getPixels() returns null, and returns that. The size-specific routines
555 perform a debugging assert that getPixels() is not null, but they do
556 not do any runtime checks.
558 void* getAddr(int x, int y) const;
560 /** Returns the address of the pixel specified by x,y for 32bit pixels.
561 * In debug build, this asserts that the pixels are allocated and locked,
562 * and that the config is 32-bit, however none of these checks are performed
563 * in the release build.
565 inline uint32_t* getAddr32(int x, int y) const;
567 /** Returns the address of the pixel specified by x,y for 16bit pixels.
568 * In debug build, this asserts that the pixels are allocated and locked,
569 * and that the config is 16-bit, however none of these checks are performed
570 * in the release build.
572 inline uint16_t* getAddr16(int x, int y) const;
574 /** Returns the address of the pixel specified by x,y for 8bit pixels.
575 * In debug build, this asserts that the pixels are allocated and locked,
576 * and that the config is 8-bit, however none of these checks are performed
577 * in the release build.
579 inline uint8_t* getAddr8(int x, int y) const;
581 /** Returns the color corresponding to the pixel specified by x,y for
582 * colortable based bitmaps.
583 * In debug build, this asserts that the pixels are allocated and locked,
584 * that the config is kIndex8, and that the colortable is allocated,
585 * however none of these checks are performed in the release build.
587 inline SkPMColor getIndex8Color(int x, int y) const;
589 /** Set dst to be a setset of this bitmap. If possible, it will share the
590 pixel memory, and just point into a subset of it. However, if the config
591 does not support this, a local copy will be made and associated with
592 the dst bitmap. If the subset rectangle, intersected with the bitmap's
593 dimensions is empty, or if there is an unsupported config, false will be
594 returned and dst will be untouched.
595 @param dst The bitmap that will be set to a subset of this bitmap
596 @param subset The rectangle of pixels in this bitmap that dst will
598 @return true if the subset copy was successfully made.
600 bool extractSubset(SkBitmap* dst, const SkIRect& subset) const;
602 /** Makes a deep copy of this bitmap, respecting the requested config,
603 * and allocating the dst pixels on the cpu.
604 * Returns false if either there is an error (i.e. the src does not have
605 * pixels) or the request cannot be satisfied (e.g. the src has per-pixel
606 * alpha, and the requested config does not support alpha).
607 * @param dst The bitmap to be sized and allocated
608 * @param c The desired config for dst
609 * @param allocator Allocator used to allocate the pixelref for the dst
610 * bitmap. If this is null, the standard HeapAllocator
612 * @return true if the copy could be made.
614 bool copyTo(SkBitmap* dst, Config c, Allocator* allocator = NULL) const;
616 /** Makes a deep copy of this bitmap, respecting the requested config, and
617 * with custom allocation logic that will keep the copied pixels
618 * in the same domain as the source: If the src pixels are allocated for
619 * the cpu, then so will the dst. If the src pixels are allocated on the
620 * gpu (typically as a texture), the it will do the same for the dst.
621 * If the request cannot be fulfilled, returns false and dst is unmodified.
623 bool deepCopyTo(SkBitmap* dst, Config c) const;
625 /** Returns true if this bitmap can be deep copied into the requested config
628 bool canCopyTo(Config newConfig) const;
630 SK_ATTR_DEPRECATED("use setFilterLevel on SkPaint")
631 void buildMipMap(bool forceRebuild = false);
633 #ifdef SK_BUILD_FOR_ANDROID
634 bool hasHardwareMipMap() const {
635 return (fFlags & kHasHardwareMipMap_Flag) != 0;
638 void setHasHardwareMipMap(bool hasHardwareMipMap) {
639 if (hasHardwareMipMap) {
640 fFlags |= kHasHardwareMipMap_Flag;
642 fFlags &= ~kHasHardwareMipMap_Flag;
647 bool extractAlpha(SkBitmap* dst) const {
648 return this->extractAlpha(dst, NULL, NULL, NULL);
651 bool extractAlpha(SkBitmap* dst, const SkPaint* paint,
652 SkIPoint* offset) const {
653 return this->extractAlpha(dst, paint, NULL, offset);
656 /** Set dst to contain alpha layer of this bitmap. If destination bitmap
657 fails to be initialized, e.g. because allocator can't allocate pixels
658 for it, dst will not be modified and false will be returned.
660 @param dst The bitmap to be filled with alpha layer
661 @param paint The paint to draw with
662 @param allocator Allocator used to allocate the pixelref for the dst
663 bitmap. If this is null, the standard HeapAllocator
665 @param offset If not null, it is set to top-left coordinate to position
666 the returned bitmap so that it visually lines up with the
669 bool extractAlpha(SkBitmap* dst, const SkPaint* paint, Allocator* allocator,
670 SkIPoint* offset) const;
672 /** The following two functions provide the means to both flatten and
673 unflatten the bitmap AND its pixels into the provided buffer.
674 It is recommended that you do not call these functions directly,
675 but instead call the write/readBitmap functions on the respective
676 buffers as they can optimize the recording process and avoid recording
677 duplicate bitmaps and pixelRefs.
679 void flatten(SkWriteBuffer&) const;
680 void unflatten(SkReadBuffer&);
682 SkDEBUGCODE(void validate() const;)
684 class Allocator : public SkRefCnt {
686 SK_DECLARE_INST_COUNT(Allocator)
688 /** Allocate the pixel memory for the bitmap, given its dimensions and
689 config. Return true on success, where success means either setPixels
690 or setPixelRef was called. The pixels need not be locked when this
691 returns. If the config requires a colortable, it also must be
692 installed via setColorTable. If false is returned, the bitmap and
693 colortable should be left unchanged.
695 virtual bool allocPixelRef(SkBitmap*, SkColorTable*) = 0;
697 typedef SkRefCnt INHERITED;
700 /** Subclass of Allocator that returns a pixelref that allocates its pixel
701 memory from the heap. This is the default Allocator invoked by
704 class HeapAllocator : public Allocator {
706 virtual bool allocPixelRef(SkBitmap*, SkColorTable*) SK_OVERRIDE;
711 RLEPixels(int width, int height);
712 virtual ~RLEPixels();
714 uint8_t* packedAtY(int y) const {
715 SkASSERT((unsigned)y < (unsigned)fHeight);
719 // called by subclasses during creation
720 void setPackedAtY(int y, uint8_t* addr) {
721 SkASSERT((unsigned)y < (unsigned)fHeight);
730 SkDEVCODE(void toString(SkString* str) const;)
734 mutable MipMap* fMipMap;
736 mutable SkPixelRef* fPixelRef;
737 mutable int fPixelLockCount;
738 // These are just caches from the locked pixelref
739 mutable void* fPixels;
740 mutable SkColorTable* fColorTable; // only meaningful for kIndex8
742 SkIPoint fPixelRefOrigin;
745 kImageIsOpaque_Flag = 0x01,
746 kImageIsVolatile_Flag = 0x02,
747 kImageIsImmutable_Flag = 0x04,
748 #ifdef SK_BUILD_FOR_ANDROID
749 /* A hint for the renderer responsible for drawing this bitmap
750 * indicating that it should attempt to use mipmaps when this bitmap
751 * is drawn scaled down.
753 kHasHardwareMipMap_Flag = 0x08,
763 void internalErase(const SkIRect&, U8CPU a, U8CPU r, U8CPU g, U8CPU b)const;
765 /* Internal computations for safe size.
767 static int64_t ComputeSafeSize64(Config config,
771 static size_t ComputeSafeSize(Config config,
776 /* Unreference any pixelrefs or colortables
779 void updatePixelsFromRef() const;
781 static SkFixed ComputeMipLevel(SkFixed sx, SkFixed dy);
783 /** Given scale factors sx, sy, determine the miplevel available in the
784 bitmap, and return it (this is the amount to shift matrix iterators
785 by). If dst is not null, it is set to the correct level.
787 int extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy);
788 bool hasMipMap() const;
791 friend struct SkBitmapProcState;
794 class SkAutoLockPixels : public SkNoncopyable {
796 SkAutoLockPixels(const SkBitmap& bm, bool doLock = true) : fBitmap(bm) {
802 ~SkAutoLockPixels() {
804 fBitmap.unlockPixels();
809 const SkBitmap& fBitmap;
812 //TODO(mtklein): uncomment when 71713004 lands and Chromium's fixed.
813 //#define SkAutoLockPixels(...) SK_REQUIRE_LOCAL_VAR(SkAutoLockPixels)
815 /** Helper class that performs the lock/unlockColors calls on a colortable.
816 The destructor will call unlockColors(false) if it has a bitmap's colortable
818 class SkAutoLockColors : public SkNoncopyable {
820 /** Initialize with no bitmap. Call lockColors(bitmap) to lock bitmap's
823 SkAutoLockColors() : fCTable(NULL), fColors(NULL) {}
824 /** Initialize with bitmap, locking its colortable if present
826 explicit SkAutoLockColors(const SkBitmap& bm) {
827 fCTable = bm.getColorTable();
828 fColors = fCTable ? fCTable->lockColors() : NULL;
830 /** Initialize with a colortable (may be null)
832 explicit SkAutoLockColors(SkColorTable* ctable) {
834 fColors = ctable ? ctable->lockColors() : NULL;
836 ~SkAutoLockColors() {
838 fCTable->unlockColors();
842 /** Return the currently locked colors, or NULL if no bitmap's colortable
845 const SkPMColor* colors() const { return fColors; }
847 /** Locks the table and returns is colors (assuming ctable is not null) and
848 unlocks the previous table if one was present
850 const SkPMColor* lockColors(SkColorTable* ctable) {
852 fCTable->unlockColors();
855 fColors = ctable ? ctable->lockColors() : NULL;
859 const SkPMColor* lockColors(const SkBitmap& bm) {
860 return this->lockColors(bm.getColorTable());
864 SkColorTable* fCTable;
865 const SkPMColor* fColors;
867 #define SkAutoLockColors(...) SK_REQUIRE_LOCAL_VAR(SkAutoLockColors)
869 ///////////////////////////////////////////////////////////////////////////////
871 inline uint32_t* SkBitmap::getAddr32(int x, int y) const {
873 SkASSERT(this->config() == kARGB_8888_Config);
874 SkASSERT((unsigned)x < (unsigned)this->width() && (unsigned)y < (unsigned)this->height());
875 return (uint32_t*)((char*)fPixels + y * fRowBytes + (x << 2));
878 inline uint16_t* SkBitmap::getAddr16(int x, int y) const {
880 SkASSERT(this->config() == kRGB_565_Config || this->config() == kARGB_4444_Config);
881 SkASSERT((unsigned)x < (unsigned)this->width() && (unsigned)y < (unsigned)this->height());
882 return (uint16_t*)((char*)fPixels + y * fRowBytes + (x << 1));
885 inline uint8_t* SkBitmap::getAddr8(int x, int y) const {
887 SkASSERT(this->config() == kA8_Config || this->config() == kIndex8_Config);
888 SkASSERT((unsigned)x < (unsigned)this->width() && (unsigned)y < (unsigned)this->height());
889 return (uint8_t*)fPixels + y * fRowBytes + x;
892 inline SkPMColor SkBitmap::getIndex8Color(int x, int y) const {
894 SkASSERT(this->config() == kIndex8_Config);
895 SkASSERT((unsigned)x < (unsigned)this->width() && (unsigned)y < (unsigned)this->height());
896 SkASSERT(fColorTable);
897 return (*fColorTable)[*((const uint8_t*)fPixels + y * fRowBytes + x)];
900 ///////////////////////////////////////////////////////////////////////////////
902 // Helpers until we can fully deprecate SkBitmap::Config
904 extern SkBitmap::Config SkColorTypeToBitmapConfig(SkColorType);
905 extern SkColorType SkBitmapConfigToColorType(SkBitmap::Config);