Home | History | Annotate | Download | only in core
      1 
      2 /*
      3  * Copyright 2006 The Android Open Source Project
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 
      9 
     10 #ifndef SkBitmap_DEFINED
     11 #define SkBitmap_DEFINED
     12 
     13 #include "Sk64.h"
     14 #include "SkColor.h"
     15 #include "SkColorTable.h"
     16 #include "SkPoint.h"
     17 #include "SkRefCnt.h"
     18 
     19 struct SkIRect;
     20 struct SkRect;
     21 class SkPaint;
     22 class SkPixelRef;
     23 class SkRegion;
     24 class SkString;
     25 
     26 class GrTexture;
     27 
     28 /** \class SkBitmap
     29 
     30     The SkBitmap class specifies a raster bitmap. A bitmap has an integer width
     31     and height, and a format (config), and a pointer to the actual pixels.
     32     Bitmaps can be drawn into a SkCanvas, but they are also used to specify the
     33     target of a SkCanvas' drawing operations.
     34     A const SkBitmap exposes getAddr(), which lets a caller write its pixels;
     35     the constness is considered to apply to the bitmap's configuration, not
     36     its contents.
     37 */
     38 class SK_API SkBitmap {
     39 public:
     40     class Allocator;
     41 
     42     enum Config {
     43         kNo_Config,         //!< bitmap has not been configured
     44         /**
     45          *  1-bit per pixel, (0 is transparent, 1 is opaque)
     46          *  Valid as a destination (target of a canvas), but not valid as a src.
     47          *  i.e. you can draw into a 1-bit bitmap, but you cannot draw from one.
     48          */
     49         kA1_Config,
     50         kA8_Config,         //!< 8-bits per pixel, with only alpha specified (0 is transparent, 0xFF is opaque)
     51         kIndex8_Config,     //!< 8-bits per pixel, using SkColorTable to specify the colors
     52         kRGB_565_Config,    //!< 16-bits per pixel, (see SkColorPriv.h for packing)
     53         kARGB_4444_Config,  //!< 16-bits per pixel, (see SkColorPriv.h for packing)
     54         kARGB_8888_Config,  //!< 32-bits per pixel, (see SkColorPriv.h for packing)
     55     };
     56 
     57     // do not add this to the Config enum, otherwise the compiler will let us
     58     // pass this as a valid parameter for Config.
     59     enum {
     60         kConfigCount = kARGB_8888_Config + 1
     61     };
     62 
     63     /**
     64      *  Default construct creates a bitmap with zero width and height, and no pixels.
     65      *  Its config is set to kNo_Config.
     66      */
     67     SkBitmap();
     68 
     69     /**
     70      *  Copy the settings from the src into this bitmap. If the src has pixels
     71      *  allocated, they will be shared, not copied, so that the two bitmaps will
     72      *  reference the same memory for the pixels. If a deep copy is needed,
     73      *  where the new bitmap has its own separate copy of the pixels, use
     74      *  deepCopyTo().
     75      */
     76     SkBitmap(const SkBitmap& src);
     77 
     78     ~SkBitmap();
     79 
     80     /** Copies the src bitmap into this bitmap. Ownership of the src bitmap's pixels remains
     81         with the src bitmap.
     82     */
     83     SkBitmap& operator=(const SkBitmap& src);
     84     /** Swap the fields of the two bitmaps. This routine is guaranteed to never fail or throw.
     85     */
     86     //  This method is not exported to java.
     87     void swap(SkBitmap& other);
     88 
     89     /** Return true iff the bitmap has empty dimensions.
     90     */
     91     bool empty() const { return 0 == fWidth || 0 == fHeight; }
     92 
     93     /** Return true iff the bitmap has no pixelref. Note: this can return true even if the
     94         dimensions of the bitmap are > 0 (see empty()).
     95     */
     96     bool isNull() const { return NULL == fPixelRef; }
     97 
     98     /** Return the config for the bitmap.
     99     */
    100     Config  config() const { return (Config)fConfig; }
    101     /** DEPRECATED, use config()
    102     */
    103     Config  getConfig() const { return this->config(); }
    104     /** Return the bitmap's width, in pixels.
    105     */
    106     int width() const { return fWidth; }
    107     /** Return the bitmap's height, in pixels.
    108     */
    109     int height() const { return fHeight; }
    110     /** Return the number of bytes between subsequent rows of the bitmap.
    111     */
    112     size_t rowBytes() const { return fRowBytes; }
    113 
    114     /** Return the shift amount per pixel (i.e. 0 for 1-byte per pixel, 1 for
    115         2-bytes per pixel configs, 2 for 4-bytes per pixel configs). Return 0
    116         for configs that are not at least 1-byte per pixel (e.g. kA1_Config
    117         or kNo_Config)
    118     */
    119     int shiftPerPixel() const { return fBytesPerPixel >> 1; }
    120 
    121     /** Return the number of bytes per pixel based on the config. If the config
    122         does not have at least 1 byte per (e.g. kA1_Config) then 0 is returned.
    123     */
    124     int bytesPerPixel() const { return fBytesPerPixel; }
    125 
    126     /** Return the rowbytes expressed as a number of pixels (like width and
    127         height). Note, for 1-byte per pixel configs like kA8_Config, this will
    128         return the same as rowBytes(). Is undefined for configs that are less
    129         than 1-byte per pixel (e.g. kA1_Config)
    130     */
    131     int rowBytesAsPixels() const { return fRowBytes >> (fBytesPerPixel >> 1); }
    132 
    133     /** Return the address of the pixels for this SkBitmap.
    134     */
    135     void* getPixels() const { return fPixels; }
    136 
    137     /** Return the byte size of the pixels, based on the height and rowBytes.
    138         Note this truncates the result to 32bits. Call getSize64() to detect
    139         if the real size exceeds 32bits.
    140     */
    141     size_t getSize() const { return fHeight * fRowBytes; }
    142 
    143     /** Return the number of bytes from the pointer returned by getPixels()
    144         to the end of the allocated space in the buffer. Required in
    145         cases where extractSubset has been called.
    146     */
    147     size_t getSafeSize() const ;
    148 
    149     /** Return the byte size of the pixels, based on the height and rowBytes.
    150         This routine is slightly slower than getSize(), but does not truncate
    151         the answer to 32bits.
    152     */
    153     Sk64 getSize64() const {
    154         Sk64 size;
    155         size.setMul(fHeight, fRowBytes);
    156         return size;
    157     }
    158 
    159     /** Same as getSafeSize(), but does not truncate the answer to 32bits.
    160     */
    161     Sk64 getSafeSize64() const ;
    162 
    163     /** Returns true if this bitmap is marked as immutable, meaning that the
    164         contents of its pixels will not change for the lifetime of the bitmap.
    165     */
    166     bool isImmutable() const;
    167 
    168     /** Marks this bitmap as immutable, meaning that the contents of its
    169         pixels will not change for the lifetime of the bitmap and of the
    170         underlying pixelref. This state can be set, but it cannot be
    171         cleared once it is set. This state propagates to all other bitmaps
    172         that share the same pixelref.
    173     */
    174     void setImmutable();
    175 
    176     /** Returns true if the bitmap is opaque (has no translucent/transparent pixels).
    177     */
    178     bool isOpaque() const;
    179 
    180     /** Specify if this bitmap's pixels are all opaque or not. Is only meaningful for configs
    181         that support per-pixel alpha (RGB32, A1, A8).
    182     */
    183     void setIsOpaque(bool);
    184 
    185     /** Returns true if the bitmap is volatile (i.e. should not be cached by devices.)
    186     */
    187     bool isVolatile() const;
    188 
    189     /** Specify whether this bitmap is volatile. Bitmaps are not volatile by
    190         default. Temporary bitmaps that are discarded after use should be
    191         marked as volatile. This provides a hint to the device that the bitmap
    192         should not be cached. Providing this hint when appropriate can
    193         improve performance by avoiding unnecessary overhead and resource
    194         consumption on the device.
    195     */
    196     void setIsVolatile(bool);
    197 
    198     /** Reset the bitmap to its initial state (see default constructor). If we are a (shared)
    199         owner of the pixels, that ownership is decremented.
    200     */
    201     void reset();
    202 
    203     /** Given a config and a width, this computes the optimal rowBytes value. This is called automatically
    204         if you pass 0 for rowBytes to setConfig().
    205     */
    206     static size_t ComputeRowBytes(Config c, int width);
    207 
    208     /** Return the bytes-per-pixel for the specified config. If the config is
    209         not at least 1-byte per pixel, return 0, including for kNo_Config.
    210     */
    211     static int ComputeBytesPerPixel(Config c);
    212 
    213     /** Return the shift-per-pixel for the specified config. If the config is
    214      not at least 1-byte per pixel, return 0, including for kNo_Config.
    215      */
    216     static int ComputeShiftPerPixel(Config c) {
    217         return ComputeBytesPerPixel(c) >> 1;
    218     }
    219 
    220     static Sk64 ComputeSize64(Config, int width, int height);
    221     static size_t ComputeSize(Config, int width, int height);
    222 
    223     /**
    224      *  This will brute-force return true if all of the pixels in the bitmap
    225      *  are opaque. If it fails to read the pixels, or encounters an error,
    226      *  it will return false.
    227      *
    228      *  Since this can be an expensive operation, the bitmap stores a flag for
    229      *  this (isOpaque, setIsOpaque). Only call this if you need to compute this
    230      *  value from "unknown" pixels.
    231      */
    232     static bool ComputeIsOpaque(const SkBitmap&);
    233 
    234     /**
    235      *  Calls ComputeIsOpaque, and passes its result to setIsOpaque().
    236      */
    237     void computeAndSetOpaquePredicate() {
    238         this->setIsOpaque(ComputeIsOpaque(*this));
    239     }
    240 
    241     /**
    242      *  Return the bitmap's bounds [0, 0, width, height] as an SkRect
    243      */
    244     void getBounds(SkRect* bounds) const;
    245     void getBounds(SkIRect* bounds) const;
    246 
    247     /** Set the bitmap's config and dimensions. If rowBytes is 0, then
    248         ComputeRowBytes() is called to compute the optimal value. This resets
    249         any pixel/colortable ownership, just like reset().
    250     */
    251     void setConfig(Config, int width, int height, size_t rowBytes = 0);
    252     /** Use this to assign a new pixel address for an existing bitmap. This
    253         will automatically release any pixelref previously installed. Only call
    254         this if you are handling ownership/lifetime of the pixel memory.
    255 
    256         If the bitmap retains a reference to the colortable (assuming it is
    257         not null) it will take care of incrementing the reference count.
    258 
    259         @param pixels   Address for the pixels, managed by the caller.
    260         @param ctable   ColorTable (or null) that matches the specified pixels
    261     */
    262     void setPixels(void* p, SkColorTable* ctable = NULL);
    263 
    264     /** Copies the bitmap's pixels to the location pointed at by dst and returns
    265         true if possible, returns false otherwise.
    266 
    267         In the case when the dstRowBytes matches the bitmap's rowBytes, the copy
    268         may be made faster by copying over the dst's per-row padding (for all
    269         rows but the last). By setting preserveDstPad to true the caller can
    270         disable this optimization and ensure that pixels in the padding are not
    271         overwritten.
    272 
    273         Always returns false for RLE formats.
    274 
    275         @param dst      Location of destination buffer.
    276         @param dstSize  Size of destination buffer. Must be large enough to hold
    277                         pixels using indicated stride.
    278         @param dstRowBytes  Width of each line in the buffer. If 0, uses
    279                             bitmap's internal stride.
    280         @param preserveDstPad Must we preserve padding in the dst
    281     */
    282     bool copyPixelsTo(void* const dst, size_t dstSize, size_t dstRowBytes = 0,
    283                       bool preserveDstPad = false) const;
    284 
    285     /** Use the standard HeapAllocator to create the pixelref that manages the
    286         pixel memory. It will be sized based on the current width/height/config.
    287         If this is called multiple times, a new pixelref object will be created
    288         each time.
    289 
    290         If the bitmap retains a reference to the colortable (assuming it is
    291         not null) it will take care of incrementing the reference count.
    292 
    293         @param ctable   ColorTable (or null) to use with the pixels that will
    294                         be allocated. Only used if config == Index8_Config
    295         @return true if the allocation succeeds. If not the pixelref field of
    296                      the bitmap will be unchanged.
    297     */
    298     bool allocPixels(SkColorTable* ctable = NULL) {
    299         return this->allocPixels(NULL, ctable);
    300     }
    301 
    302     /** Use the specified Allocator to create the pixelref that manages the
    303         pixel memory. It will be sized based on the current width/height/config.
    304         If this is called multiple times, a new pixelref object will be created
    305         each time.
    306 
    307         If the bitmap retains a reference to the colortable (assuming it is
    308         not null) it will take care of incrementing the reference count.
    309 
    310         @param allocator The Allocator to use to create a pixelref that can
    311                          manage the pixel memory for the current
    312                          width/height/config. If allocator is NULL, the standard
    313                          HeapAllocator will be used.
    314         @param ctable   ColorTable (or null) to use with the pixels that will
    315                         be allocated. Only used if config == Index8_Config.
    316                         If it is non-null and the config is not Index8, it will
    317                         be ignored.
    318         @return true if the allocation succeeds. If not the pixelref field of
    319                      the bitmap will be unchanged.
    320     */
    321     bool allocPixels(Allocator* allocator, SkColorTable* ctable);
    322 
    323     /** Return the current pixelref object, if any
    324     */
    325     SkPixelRef* pixelRef() const { return fPixelRef; }
    326     /** Return the offset into the pixelref, if any. Will return 0 if there is
    327         no pixelref installed.
    328     */
    329     size_t pixelRefOffset() const { return fPixelRefOffset; }
    330     /** Assign a pixelref and optional offset. Pixelrefs are reference counted,
    331         so the existing one (if any) will be unref'd and the new one will be
    332         ref'd.
    333     */
    334     SkPixelRef* setPixelRef(SkPixelRef* pr, size_t offset = 0);
    335 
    336     /** Call this to ensure that the bitmap points to the current pixel address
    337         in the pixelref. Balance it with a call to unlockPixels(). These calls
    338         are harmless if there is no pixelref.
    339     */
    340     void lockPixels() const;
    341     /** When you are finished access the pixel memory, call this to balance a
    342         previous call to lockPixels(). This allows pixelrefs that implement
    343         cached/deferred image decoding to know when there are active clients of
    344         a given image.
    345     */
    346     void unlockPixels() const;
    347 
    348     /**
    349      *  Some bitmaps can return a copy of their pixels for lockPixels(), but
    350      *  that copy, if modified, will not be pushed back. These bitmaps should
    351      *  not be used as targets for a raster device/canvas (since all pixels
    352      *  modifications will be lost when unlockPixels() is called.)
    353      */
    354     bool lockPixelsAreWritable() const;
    355 
    356     /** Call this to be sure that the bitmap is valid enough to be drawn (i.e.
    357         it has non-null pixels, and if required by its config, it has a
    358         non-null colortable. Returns true if all of the above are met.
    359     */
    360     bool readyToDraw() const {
    361         return this->getPixels() != NULL &&
    362                (this->config() != kIndex8_Config || NULL != fColorTable);
    363     }
    364 
    365     /** Returns the pixelRef's texture, or NULL
    366      */
    367     GrTexture* getTexture() const;
    368 
    369     /** Return the bitmap's colortable, if it uses one (i.e. fConfig is
    370         kIndex8_Config) and the pixels are locked.
    371         Otherwise returns NULL. Does not affect the colortable's
    372         reference count.
    373     */
    374     SkColorTable* getColorTable() const { return fColorTable; }
    375 
    376     /** Returns a non-zero, unique value corresponding to the pixels in our
    377         pixelref. Each time the pixels are changed (and notifyPixelsChanged
    378         is called), a different generation ID will be returned. Finally, if
    379         their is no pixelRef then zero is returned.
    380     */
    381     uint32_t getGenerationID() const;
    382 
    383     /** Call this if you have changed the contents of the pixels. This will in-
    384         turn cause a different generation ID value to be returned from
    385         getGenerationID().
    386     */
    387     void notifyPixelsChanged() const;
    388 
    389     /**
    390      *  Fill the entire bitmap with the specified color.
    391      *  If the bitmap's config does not support alpha (e.g. 565) then the alpha
    392      *  of the color is ignored (treated as opaque). If the config only supports
    393      *  alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
    394      */
    395     void eraseColor(SkColor c) const {
    396         this->eraseARGB(SkColorGetA(c), SkColorGetR(c), SkColorGetG(c),
    397                         SkColorGetB(c));
    398     }
    399 
    400     /**
    401      *  Fill the entire bitmap with the specified color.
    402      *  If the bitmap's config does not support alpha (e.g. 565) then the alpha
    403      *  of the color is ignored (treated as opaque). If the config only supports
    404      *  alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
    405      */
    406     void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const;
    407 
    408     // DEPRECATED -- call eraseColor or eraseARGB
    409     void eraseRGB(U8CPU r, U8CPU g, U8CPU b) const {
    410         this->eraseARGB(0xFF, r, g, b);
    411     }
    412 
    413     /**
    414      *  Fill the specified area of this bitmap with the specified color.
    415      *  If the bitmap's config does not support alpha (e.g. 565) then the alpha
    416      *  of the color is ignored (treated as opaque). If the config only supports
    417      *  alpha (e.g. A1 or A8) then the color's r,g,b components are ignored.
    418      */
    419     void eraseArea(const SkIRect& area, SkColor c) const;
    420 
    421     /** Scroll (a subset of) the contents of this bitmap by dx/dy. If there are
    422         no pixels allocated (i.e. getPixels() returns null) the method will
    423         still update the inval region (if present). If the bitmap is immutable,
    424         do nothing and return false.
    425 
    426         @param subset The subset of the bitmap to scroll/move. To scroll the
    427                       entire contents, specify [0, 0, width, height] or just
    428                       pass null.
    429         @param dx The amount to scroll in X
    430         @param dy The amount to scroll in Y
    431         @param inval Optional (may be null). Returns the area of the bitmap that
    432                      was scrolled away. E.g. if dx = dy = 0, then inval would
    433                      be set to empty. If dx >= width or dy >= height, then
    434                      inval would be set to the entire bounds of the bitmap.
    435         @return true if the scroll was doable. Will return false if the bitmap
    436                      uses an unsupported config for scrolling (only kA8,
    437                      kIndex8, kRGB_565, kARGB_4444, kARGB_8888 are supported).
    438                      If no pixels are present (i.e. getPixels() returns false)
    439                      inval will still be updated, and true will be returned.
    440     */
    441     bool scrollRect(const SkIRect* subset, int dx, int dy,
    442                     SkRegion* inval = NULL) const;
    443 
    444     /**
    445      *  Return the SkColor of the specified pixel.  In most cases this will
    446      *  require un-premultiplying the color.  Alpha only configs (A1 and A8)
    447      *  return black with the appropriate alpha set.  The value is undefined
    448      *  for kNone_Config or if x or y are out of bounds, or if the bitmap
    449      *  does not have any pixels (or has not be locked with lockPixels()).
    450      */
    451     SkColor getColor(int x, int y) const;
    452 
    453     /** Returns the address of the specified pixel. This performs a runtime
    454         check to know the size of the pixels, and will return the same answer
    455         as the corresponding size-specific method (e.g. getAddr16). Since the
    456         check happens at runtime, it is much slower than using a size-specific
    457         version. Unlike the size-specific methods, this routine also checks if
    458         getPixels() returns null, and returns that. The size-specific routines
    459         perform a debugging assert that getPixels() is not null, but they do
    460         not do any runtime checks.
    461     */
    462     void* getAddr(int x, int y) const;
    463 
    464     /** Returns the address of the pixel specified by x,y for 32bit pixels.
    465      *  In debug build, this asserts that the pixels are allocated and locked,
    466      *  and that the config is 32-bit, however none of these checks are performed
    467      *  in the release build.
    468      */
    469     inline uint32_t* getAddr32(int x, int y) const;
    470 
    471     /** Returns the address of the pixel specified by x,y for 16bit pixels.
    472      *  In debug build, this asserts that the pixels are allocated and locked,
    473      *  and that the config is 16-bit, however none of these checks are performed
    474      *  in the release build.
    475      */
    476     inline uint16_t* getAddr16(int x, int y) const;
    477 
    478     /** Returns the address of the pixel specified by x,y for 8bit pixels.
    479      *  In debug build, this asserts that the pixels are allocated and locked,
    480      *  and that the config is 8-bit, however none of these checks are performed
    481      *  in the release build.
    482      */
    483     inline uint8_t* getAddr8(int x, int y) const;
    484 
    485     /** Returns the address of the byte containing the pixel specified by x,y
    486      *  for 1bit pixels.
    487      *  In debug build, this asserts that the pixels are allocated and locked,
    488      *  and that the config is 1-bit, however none of these checks are performed
    489      *  in the release build.
    490      */
    491     inline uint8_t* getAddr1(int x, int y) const;
    492 
    493     /** Returns the color corresponding to the pixel specified by x,y for
    494      *  colortable based bitmaps.
    495      *  In debug build, this asserts that the pixels are allocated and locked,
    496      *  that the config is kIndex8, and that the colortable is allocated,
    497      *  however none of these checks are performed in the release build.
    498      */
    499     inline SkPMColor getIndex8Color(int x, int y) const;
    500 
    501     /** Set dst to be a setset of this bitmap. If possible, it will share the
    502         pixel memory, and just point into a subset of it. However, if the config
    503         does not support this, a local copy will be made and associated with
    504         the dst bitmap. If the subset rectangle, intersected with the bitmap's
    505         dimensions is empty, or if there is an unsupported config, false will be
    506         returned and dst will be untouched.
    507         @param dst  The bitmap that will be set to a subset of this bitmap
    508         @param subset The rectangle of pixels in this bitmap that dst will
    509                       reference.
    510         @return true if the subset copy was successfully made.
    511     */
    512     bool extractSubset(SkBitmap* dst, const SkIRect& subset) const;
    513 
    514     /** Makes a deep copy of this bitmap, respecting the requested config,
    515      *  and allocating the dst pixels on the cpu.
    516      *  Returns false if either there is an error (i.e. the src does not have
    517      *  pixels) or the request cannot be satisfied (e.g. the src has per-pixel
    518      *  alpha, and the requested config does not support alpha).
    519      *  @param dst The bitmap to be sized and allocated
    520      *  @param c The desired config for dst
    521      *  @param allocator Allocator used to allocate the pixelref for the dst
    522      *                   bitmap. If this is null, the standard HeapAllocator
    523      *                   will be used.
    524      *  @return true if the copy could be made.
    525      */
    526     bool copyTo(SkBitmap* dst, Config c, Allocator* allocator = NULL) const;
    527 
    528     /** Makes a deep copy of this bitmap, respecting the requested config, and
    529      *  with custom allocation logic that will keep the copied pixels
    530      *  in the same domain as the source: If the src pixels are allocated for
    531      *  the cpu, then so will the dst. If the src pixels are allocated on the
    532      *  gpu (typically as a texture), the it will do the same for the dst.
    533      *  If the request cannot be fulfilled, returns false and dst is unmodified.
    534      */
    535     bool deepCopyTo(SkBitmap* dst, Config c) const;
    536 
    537     /** Returns true if this bitmap can be deep copied into the requested config
    538         by calling copyTo().
    539      */
    540     bool canCopyTo(Config newConfig) const;
    541 
    542     /**
    543      *  DEPRECATED -- will be replaced with API on SkPaint
    544      */
    545     void buildMipMap(bool forceRebuild = false);
    546 
    547 #ifdef SK_BUILD_FOR_ANDROID
    548     bool hasHardwareMipMap() const {
    549         return (fFlags & kHasHardwareMipMap_Flag) != 0;
    550     }
    551 
    552     void setHasHardwareMipMap(bool hasHardwareMipMap) {
    553         if (hasHardwareMipMap) {
    554             fFlags |= kHasHardwareMipMap_Flag;
    555         } else {
    556             fFlags &= ~kHasHardwareMipMap_Flag;
    557         }
    558     }
    559 #endif
    560 
    561     bool extractAlpha(SkBitmap* dst) const {
    562         return this->extractAlpha(dst, NULL, NULL, NULL);
    563     }
    564 
    565     bool extractAlpha(SkBitmap* dst, const SkPaint* paint,
    566                       SkIPoint* offset) const {
    567         return this->extractAlpha(dst, paint, NULL, offset);
    568     }
    569 
    570     /** Set dst to contain alpha layer of this bitmap. If destination bitmap
    571         fails to be initialized, e.g. because allocator can't allocate pixels
    572         for it, dst will not be modified and false will be returned.
    573 
    574         @param dst The bitmap to be filled with alpha layer
    575         @param paint The paint to draw with
    576         @param allocator Allocator used to allocate the pixelref for the dst
    577                          bitmap. If this is null, the standard HeapAllocator
    578                          will be used.
    579         @param offset If not null, it is set to top-left coordinate to position
    580                       the returned bitmap so that it visually lines up with the
    581                       original
    582     */
    583     bool extractAlpha(SkBitmap* dst, const SkPaint* paint, Allocator* allocator,
    584                       SkIPoint* offset) const;
    585 
    586     /** The following two functions provide the means to both flatten and
    587         unflatten the bitmap AND its pixels into the provided buffer.
    588         It is recommended that you do not call these functions directly,
    589         but instead call the write/readBitmap functions on the respective
    590         buffers as they can optimize the recording process and avoid recording
    591         duplicate bitmaps and pixelRefs.
    592      */
    593     void flatten(SkFlattenableWriteBuffer&) const;
    594     void unflatten(SkFlattenableReadBuffer&);
    595 
    596     SkDEBUGCODE(void validate() const;)
    597 
    598     class Allocator : public SkRefCnt {
    599     public:
    600         SK_DECLARE_INST_COUNT(Allocator)
    601 
    602         /** Allocate the pixel memory for the bitmap, given its dimensions and
    603             config. Return true on success, where success means either setPixels
    604             or setPixelRef was called. The pixels need not be locked when this
    605             returns. If the config requires a colortable, it also must be
    606             installed via setColorTable. If false is returned, the bitmap and
    607             colortable should be left unchanged.
    608         */
    609         virtual bool allocPixelRef(SkBitmap*, SkColorTable*) = 0;
    610     private:
    611         typedef SkRefCnt INHERITED;
    612     };
    613 
    614     /** Subclass of Allocator that returns a pixelref that allocates its pixel
    615         memory from the heap. This is the default Allocator invoked by
    616         allocPixels().
    617     */
    618     class HeapAllocator : public Allocator {
    619     public:
    620         virtual bool allocPixelRef(SkBitmap*, SkColorTable*);
    621     };
    622 
    623     class RLEPixels {
    624     public:
    625         RLEPixels(int width, int height);
    626         virtual ~RLEPixels();
    627 
    628         uint8_t* packedAtY(int y) const {
    629             SkASSERT((unsigned)y < (unsigned)fHeight);
    630             return fYPtrs[y];
    631         }
    632 
    633         // called by subclasses during creation
    634         void setPackedAtY(int y, uint8_t* addr) {
    635             SkASSERT((unsigned)y < (unsigned)fHeight);
    636             fYPtrs[y] = addr;
    637         }
    638 
    639     private:
    640         uint8_t** fYPtrs;
    641         int       fHeight;
    642     };
    643 
    644     SkDEVCODE(void toString(SkString* str) const;)
    645 
    646 private:
    647     struct MipMap;
    648     mutable MipMap* fMipMap;
    649 
    650     mutable SkPixelRef* fPixelRef;
    651     mutable size_t      fPixelRefOffset;
    652     mutable int         fPixelLockCount;
    653     // either user-specified (in which case it is not treated as mutable)
    654     // or a cache of the returned value from fPixelRef->lockPixels()
    655     mutable void*       fPixels;
    656     mutable SkColorTable* fColorTable;    // only meaningful for kIndex8
    657 
    658     enum Flags {
    659         kImageIsOpaque_Flag     = 0x01,
    660         kImageIsVolatile_Flag   = 0x02,
    661         kImageIsImmutable_Flag  = 0x04,
    662 #ifdef SK_BUILD_FOR_ANDROID
    663         /* A hint for the renderer responsible for drawing this bitmap
    664          * indicating that it should attempt to use mipmaps when this bitmap
    665          * is drawn scaled down.
    666          */
    667         kHasHardwareMipMap_Flag = 0x08,
    668 #endif
    669     };
    670 
    671     uint32_t    fRowBytes;
    672     uint32_t    fWidth;
    673     uint32_t    fHeight;
    674     uint8_t     fConfig;
    675     uint8_t     fFlags;
    676     uint8_t     fBytesPerPixel; // based on config
    677 
    678     void internalErase(const SkIRect&, U8CPU a, U8CPU r, U8CPU g, U8CPU b)const;
    679 
    680     /* Internal computations for safe size.
    681     */
    682     static Sk64 ComputeSafeSize64(Config   config,
    683                                   uint32_t width,
    684                                   uint32_t height,
    685                                   size_t   rowBytes);
    686     static size_t ComputeSafeSize(Config   config,
    687                                   uint32_t width,
    688                                   uint32_t height,
    689                                   size_t   rowBytes);
    690 
    691     /*  Unreference any pixelrefs or colortables
    692     */
    693     void freePixels();
    694     void updatePixelsFromRef() const;
    695 
    696     static SkFixed ComputeMipLevel(SkFixed sx, SkFixed dy);
    697 
    698     /** Given scale factors sx, sy, determine the miplevel available in the
    699      bitmap, and return it (this is the amount to shift matrix iterators
    700      by). If dst is not null, it is set to the correct level.
    701      */
    702     int extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy);
    703     bool hasMipMap() const;
    704     void freeMipMap();
    705 
    706     friend struct SkBitmapProcState;
    707 };
    708 
    709 class SkAutoLockPixels : public SkNoncopyable {
    710 public:
    711     SkAutoLockPixels(const SkBitmap& bm, bool doLock = true) : fBitmap(bm) {
    712         fDidLock = doLock;
    713         if (doLock) {
    714             bm.lockPixels();
    715         }
    716     }
    717     ~SkAutoLockPixels() {
    718         if (fDidLock) {
    719             fBitmap.unlockPixels();
    720         }
    721     }
    722 
    723 private:
    724     const SkBitmap& fBitmap;
    725     bool            fDidLock;
    726 };
    727 
    728 /** Helper class that performs the lock/unlockColors calls on a colortable.
    729     The destructor will call unlockColors(false) if it has a bitmap's colortable
    730 */
    731 class SkAutoLockColors : public SkNoncopyable {
    732 public:
    733     /** Initialize with no bitmap. Call lockColors(bitmap) to lock bitmap's
    734         colortable
    735      */
    736     SkAutoLockColors() : fCTable(NULL), fColors(NULL) {}
    737     /** Initialize with bitmap, locking its colortable if present
    738      */
    739     explicit SkAutoLockColors(const SkBitmap& bm) {
    740         fCTable = bm.getColorTable();
    741         fColors = fCTable ? fCTable->lockColors() : NULL;
    742     }
    743     /** Initialize with a colortable (may be null)
    744      */
    745     explicit SkAutoLockColors(SkColorTable* ctable) {
    746         fCTable = ctable;
    747         fColors = ctable ? ctable->lockColors() : NULL;
    748     }
    749     ~SkAutoLockColors() {
    750         if (fCTable) {
    751             fCTable->unlockColors(false);
    752         }
    753     }
    754 
    755     /** Return the currently locked colors, or NULL if no bitmap's colortable
    756         is currently locked.
    757     */
    758     const SkPMColor* colors() const { return fColors; }
    759 
    760     /** Locks the table and returns is colors (assuming ctable is not null) and
    761         unlocks the previous table if one was present
    762      */
    763     const SkPMColor* lockColors(SkColorTable* ctable) {
    764         if (fCTable) {
    765             fCTable->unlockColors(false);
    766         }
    767         fCTable = ctable;
    768         fColors = ctable ? ctable->lockColors() : NULL;
    769         return fColors;
    770     }
    771 
    772     const SkPMColor* lockColors(const SkBitmap& bm) {
    773         return this->lockColors(bm.getColorTable());
    774     }
    775 
    776 private:
    777     SkColorTable*    fCTable;
    778     const SkPMColor* fColors;
    779 };
    780 
    781 ///////////////////////////////////////////////////////////////////////////////
    782 
    783 inline uint32_t* SkBitmap::getAddr32(int x, int y) const {
    784     SkASSERT(fPixels);
    785     SkASSERT(fConfig == kARGB_8888_Config);
    786     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    787     return (uint32_t*)((char*)fPixels + y * fRowBytes + (x << 2));
    788 }
    789 
    790 inline uint16_t* SkBitmap::getAddr16(int x, int y) const {
    791     SkASSERT(fPixels);
    792     SkASSERT(fConfig == kRGB_565_Config || fConfig == kARGB_4444_Config);
    793     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    794     return (uint16_t*)((char*)fPixels + y * fRowBytes + (x << 1));
    795 }
    796 
    797 inline uint8_t* SkBitmap::getAddr8(int x, int y) const {
    798     SkASSERT(fPixels);
    799     SkASSERT(fConfig == kA8_Config || fConfig == kIndex8_Config);
    800     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    801     return (uint8_t*)fPixels + y * fRowBytes + x;
    802 }
    803 
    804 inline SkPMColor SkBitmap::getIndex8Color(int x, int y) const {
    805     SkASSERT(fPixels);
    806     SkASSERT(fConfig == kIndex8_Config);
    807     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    808     SkASSERT(fColorTable);
    809     return (*fColorTable)[*((const uint8_t*)fPixels + y * fRowBytes + x)];
    810 }
    811 
    812 // returns the address of the byte that contains the x coordinate
    813 inline uint8_t* SkBitmap::getAddr1(int x, int y) const {
    814     SkASSERT(fPixels);
    815     SkASSERT(fConfig == kA1_Config);
    816     SkASSERT((unsigned)x < fWidth && (unsigned)y < fHeight);
    817     return (uint8_t*)fPixels + y * fRowBytes + (x >> 3);
    818 }
    819 
    820 #endif
    821