- Практический опыт работы с Bitmap средствами Android
- Exploring Android Canvas Drawing— For Shapes, Bitmaps andCustom views.
- So what exactly is Android Canvas ?
- Your mobile screen is your canvas
- Create your own custom view class
- The magic methods : onDraw() and invalidate()
- Drawing basics
- Draw Line
- Draw Circle
- Draw Rectangle
- Draw Square
- Getting tougher : Draw Triangle ()
- Update Canvas
- View or SurfaceView ?
- Практический опыт работы с Bitmap средствами Android
- Bitmap
- Summary
- Constants
- public static final int DENSITY_NONE
- Fields
- public static final Creator CREATOR
- Public Methods
- public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
- public Bitmap copy (Bitmap.Config config, boolean isMutable)
- public void copyPixelsFromBuffer (Buffer src)
- public void copyPixelsToBuffer (Buffer dst)
- public static Bitmap createBitmap (DisplayMetrics display, int[] colors, int width, int height, Bitmap.Config config)
- public static Bitmap createBitmap (DisplayMetrics display, int width, int height, Bitmap.Config config)
- public void eraseColor (int c)
- public Bitmap extractAlpha ()
- public Bitmap extractAlpha (Paint paint, int[] offsetXY)
- public final int getAllocationByteCount ()
- public final int getByteCount ()
- public final Bitmap.Config getConfig ()
- public int getDensity ()
- public int getGenerationId ()
- public final int getHeight ()
- public byte[] getNinePatchChunk ()
- public int getPixel (int x, int y)
- public void getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)
- public int getScaledHeight (DisplayMetrics metrics)
- public int getScaledHeight (int targetDensity)
- public int getScaledHeight (Canvas canvas)
- public int getScaledWidth (int targetDensity)
- public int getScaledWidth (DisplayMetrics metrics)
- public int getScaledWidth (Canvas canvas)
- public final int getWidth ()
- public final boolean hasAlpha ()
- public final boolean hasMipMap ()
- public final boolean isMutable ()
- public final boolean isPremultiplied ()
- public final boolean isRecycled ()
- public void prepareToDraw ()
- public void reconfigure (int width, int height, Bitmap.Config config)
- public void recycle ()
- public boolean sameAs (Bitmap other)
- public void setConfig (Bitmap.Config config)
- public void setDensity (int density)
- public void setHasAlpha (boolean hasAlpha)
- public final void setHasMipMap (boolean hasMipMap)
Практический опыт работы с Bitmap средствами Android
Не так давно по долгу службы я столкнулся с одной задачей: нужно было придумать и реализовать дизайн медиа-плеера для Android. И если продумать и организовать более или менее сносное размещение элементов управления и информации оказалось делом не хитрым, то чтобы привнести в дизайн какую-то изюминку, пришлось хорошенько подумать. К счастью, в запасе у меня был такой элемент, как картинка с обложкой альбома проигрываемой мелодии. Именно он должен был добавить красок всей картинке.
Однако, будучи просто выведенной среди кнопок и надписей, обложка выглядела бумажным стикером, наклеенным на экран. Я понял, что без обработки изображения здесь не обойтись.
Некоторые раздумья насчёт того, что можно было бы тут придумать увенчались решением сделать для изображения обложки эффект отражения и тени. Сразу оговорюсь, что практическая реализация отражения не является моей оригинальной идеей. Её я подсмотрел в найденной англоязычной статье. В настоящем посте я лишь хочу привести некоторое осмысление производимых над изображением манипуляций, свои дополнения к процессу обработки и отметить некоторые нюансы работы с Bitmap в Android.
Итак, на входе я имел Bitmap с картинкой. Для начала я создал пустой Bitmap размером с оригинальную картинку, который позже должен был стать той же обложкой, но с нанесённой на неё тенью.
Этот метод создаёт изменяемый (что важно) Bitmap.
Здесь обязательно нужно отметить, что при работе с Bitmap’ами необходимо внимательно следить за памятью. Придётся ловить исключения. И ещё один момент: изучение профайлером показало, что перед вызовом метода createBitmap() работает сборщик мусора. Учтите это, если в вашем приложении скорость работы критична.
Далее я создал холст и нанёс на него исходное изображение.
В этом месте отмечу, что всегда, как только Bitmap становится не нужен, его нужно уничтожать методом recycle(). Дело в том, что объект этого типа представляет собой всего лишь ссылку на память с самим изображением и выглядит для сборщика мусора очень маленьким (хотя на самом деле памяти занято много). Это может привести к тому, что память закончится в самый неподходящий момент.
После всей подготовки я нанёс на холст краску с тенью.
RadialGradient в моём случае представляет тень, падающую по полукругу из правого верхнего угла изображения в центр нижней грани. Ему нужно установить центр (может выходить за пределы картинки), радиус, последовательность цветов и расстояния от центра по радиусу для каждого цвета. Для тени использовалось изменение альфы в цветах на радиусе.
LinearGradient использовался для фэйда краёв картинки. Его применение очень похоже на RadialGradient. Нужно задать начало и конец линии, вдоль которой пойдёт градиент, цвета и их позиции на этой линии.
Наконец, я приступил к рисованию отражения. К этому моменту у меня уже был Bitmap с нанесёнными тенями gradBitmap. Опять надо было создавать холст, создавать пустое изображение (на этот раз на треть длиннее оригинального), помещать его на холст и наносить на верх него Bitmap с тенями.
После недолгих приготовлений начиналось самое интересное. Я создал матрицу, переворачивающую изображение снизу вверх. С её помощью создал Bitmap из трети исходного и нанёс его на холст под оригинальным изображением.
Кстати, краткое замечание: в классе Bitmap существует несколько методов createBitmap, и лишь один из них создаёт изменяемые Bitmap’ы, на которых можно рисовать. Остальные для рисования НА них не годятся.
И наконец, нанесение прозрачного градиента для придания эффекта отражения.
Краска наносится на ту часть рисунка, которая является отражением.
Всё. Я получил refCover — Bitmap, на котором изображена обложка альбома с тенью, сглаженными краями и отражением.
P.S. В данной статье для меня был важен не сам факт достижения визуальных эффектов, а способы их получения и нюансы, с ними связанные. Если для кого-то вещи, описанные здесь, очевидны — прекрасно. Всем остальным, я надеюсь, статья поможет в написании своих приложений под Android.
UPD: картинки ДО и ПОСЛЕ
Источник
Exploring Android Canvas Drawing— For Shapes, Bitmaps andCustom views.
Jan 9, 2019 · 6 min read
Would you like to
- Create your own drawing (UI) on the screen OR create custom views ?
- Modify existing views and customize their look and feel ?
- Draw any shape, view or just bitmaps ?
- Create something which isn’t already available ?
The power of Android for free hand drawing on pen and paper !
Android Canvas gives you exactly that. Just dive in and create your own magic.
If you know the basics and directly want to view the code, find the entire source code here on GitHub.
So what exactly is Android Canvas ?
The Android framework APIs provides a set of 2D d r awing APIs that allow you to render your own custom graphics onto a canvas or to modify existing Views to customize their look and feel. Basically, Canvas is a class in Android that performs 2D drawing onto the screen of different objects.
Your mobile screen is your canvas
Just consider you mobile screen as a blank paper and draw on it. You need to define anchor points and shapes so as to draw on the screen. Remember the school level graphs ? Something very similar.
Define X & Y coordinates and the shape you want.
Create your own custom view class
Just create custom view class. Since you want to draw your own UI , extend View class to get the lifecycle of the basic view hierarchy.
Define a paint object with default colors and styling
Create and initialise the paint object in your constructor only. Most of the times, our basic settings don’t change. We can then use this paint object every where else in the code and only change properties we want.
The magic methods : onDraw() and invalidate()
All of canvas drawing will happen in onDraw method. Whenever you want to draw any custom objects , you set the paint styling, call default draw.. API methods. All these internally call onDraw.
Get your canvas instance in onDraw and save it for drawing.
Every time, you draw something new on the canvas , you need to refresh it. Your entire canvas is re-drawn. And hence you need to perform minimal operations in onDraw().
To tell the view, that is has to refresh use invalidate() method.
Remember our paint object is initialised in constructor so that we don’t create it again and again on draw. OnDraw gets called every single time you want to change anything on the UI. So it’s an expensive call. We don’t want to do anything extra than required on onDraw method.
Drawing basics
A variety of basic draw API’s are available on the canvas object. We can use these basic API;s to create our own custom shapes and figures. some common ones are :
- drawCircle
- drawLine
- drawOval
- drawPoints
- drawText
- drawRect
- drawPath
Draw Line
You define the two points with their x, y coordinates and draw path between them.
Draw Circle
The simplest shape. You just need to specify the x coordinate, y coordinate on the screen and the radius. Also set any paint color if you want.
Draw Rectangle
Create a rectangle with x, y, height, width.
Draw Square
Create a rectangle object, with the required coordinates, with the same width and height.
Getting tougher : Draw Triangle ()
Triangle is basically three vertices connected with a line. You need to find those three vertices and draw a line between them.
Below we draw an equilateral triangle
Update Canvas
If you follow the MVP / MVVM / etc other architectural pattern, you might want to refresh your canvas from other layers. Just get the canvas object , do all your business logic for drawing, and then run invalidate.
View or SurfaceView ?
If you want to know more about multi-threading
[Use View : If your application does not require a significant amount of processing or frame-rate speed (perhaps for a chess game, a snake game, or another slowly-animated application). In the same thread as your UI Activity, wherein you create a custom View component in your layout, call invalidate() and then handle the onDraw() callback.
Use SurfaceView — If you have high computation or so the application doesn’t to wait until the system’s View hierarchy is ready to draw and want to run in a separate thread, wherein you manage a SurfaceView and perform draws to the Canvas as fast as your thread is capable (you do not need to request invalidate() )]
You can deep dive into the code here on GitHub and check out details there.
In the next article, we will learn more on handling touch events on Canvas like touch, click, long press, etc.
Thats’ it. Thank you for reading. Please let me know what you liked in the article and what would you like to know more.
Источник
Практический опыт работы с Bitmap средствами Android
Не так давно по долгу службы я столкнулся с одной задачей: нужно было придумать и реализовать дизайн медиа-плеера для Android. И если продумать и организовать более или менее сносное размещение элементов управления и информации оказалось делом не хитрым, то чтобы привнести в дизайн какую-то изюминку, пришлось хорошенько подумать. К счастью, в запасе у меня был такой элемент, как картинка с обложкой альбома проигрываемой мелодии. Именно он должен был добавить красок всей картинке.
Однако, будучи просто выведенной среди кнопок и надписей, обложка выглядела бумажным стикером, наклеенным на экран. Я понял, что без обработки изображения здесь не обойтись.
Некоторые раздумья насчёт того, что можно было бы тут придумать увенчались решением сделать для изображения обложки эффект отражения и тени. Сразу оговорюсь, что практическая реализация отражения не является моей оригинальной идеей. Её я подсмотрел в найденной англоязычной статье. В настоящем посте я лишь хочу привести некоторое осмысление производимых над изображением манипуляций, свои дополнения к процессу обработки и отметить некоторые нюансы работы с Bitmap в Android.
Итак, на входе я имел Bitmap с картинкой. Для начала я создал пустой Bitmap размером с оригинальную картинку, который позже должен был стать той же обложкой, но с нанесённой на неё тенью.
Этот метод создаёт изменяемый (что важно) Bitmap.
Здесь обязательно нужно отметить, что при работе с Bitmap’ами необходимо внимательно следить за памятью. Придётся ловить исключения. И ещё один момент: изучение профайлером показало, что перед вызовом метода createBitmap() работает сборщик мусора. Учтите это, если в вашем приложении скорость работы критична.
Далее я создал холст и нанёс на него исходное изображение.
В этом месте отмечу, что всегда, как только Bitmap становится не нужен, его нужно уничтожать методом recycle(). Дело в том, что объект этого типа представляет собой всего лишь ссылку на память с самим изображением и выглядит для сборщика мусора очень маленьким (хотя на самом деле памяти занято много). Это может привести к тому, что память закончится в самый неподходящий момент.
После всей подготовки я нанёс на холст краску с тенью.
RadialGradient в моём случае представляет тень, падающую по полукругу из правого верхнего угла изображения в центр нижней грани. Ему нужно установить центр (может выходить за пределы картинки), радиус, последовательность цветов и расстояния от центра по радиусу для каждого цвета. Для тени использовалось изменение альфы в цветах на радиусе.
LinearGradient использовался для фэйда краёв картинки. Его применение очень похоже на RadialGradient. Нужно задать начало и конец линии, вдоль которой пойдёт градиент, цвета и их позиции на этой линии.
Наконец, я приступил к рисованию отражения. К этому моменту у меня уже был Bitmap с нанесёнными тенями gradBitmap. Опять надо было создавать холст, создавать пустое изображение (на этот раз на треть длиннее оригинального), помещать его на холст и наносить на верх него Bitmap с тенями.
После недолгих приготовлений начиналось самое интересное. Я создал матрицу, переворачивающую изображение снизу вверх. С её помощью создал Bitmap из трети исходного и нанёс его на холст под оригинальным изображением.
Кстати, краткое замечание: в классе Bitmap существует несколько методов createBitmap, и лишь один из них создаёт изменяемые Bitmap’ы, на которых можно рисовать. Остальные для рисования НА них не годятся.
И наконец, нанесение прозрачного градиента для придания эффекта отражения.
Краска наносится на ту часть рисунка, которая является отражением.
Всё. Я получил refCover — Bitmap, на котором изображена обложка альбома с тенью, сглаженными краями и отражением.
P.S. В данной статье для меня был важен не сам факт достижения визуальных эффектов, а способы их получения и нюансы, с ними связанные. Если для кого-то вещи, описанные здесь, очевидны — прекрасно. Всем остальным, я надеюсь, статья поможет в написании своих приложений под Android.
UPD: картинки ДО и ПОСЛЕ
Источник
Bitmap
Summary
Nested Classes | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Bitmap.CompressFormat | Specifies the known formats a bitmap can be compressed into | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Bitmap.Config | Possible bitmap configurations. |
Constants | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
int | DENSITY_NONE | Indicates that the bitmap was created for an unknown pixel density. |
[Expand]
Copy the pixels from the buffer, beginning at the current position, overwriting the bitmap’s pixels. Copy the bitmap’s pixels into the specified buffer (allocated by the caller). Returns the density for this bitmap. Indicates whether pixels stored in this bitmaps are stored pre-multiplied. Modifies the bitmap to have a specified width, height, and Bitmap.Config , without affecting the underlying allocation backing the bitmap. Convenience method for calling reconfigure(int, int, Config) with the current height and width. Specifies the density for this bitmap. Convenience method for calling reconfigure(int, int, Config) with the current width and config. Write the specified Color into the bitmap (assuming it is mutable) at the x,y coordinate. Replace pixels in the bitmap with the colors in the array. Convenience method for calling reconfigure(int, int, Config) with the current height and config. Constantspublic static final int DENSITY_NONEIndicates that the bitmap was created for an unknown pixel density. See AlsoFieldspublic static final Creator CREATORPublic Methodspublic boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)Write a compressed version of the bitmap to the specified outputstream. If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream(). Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels). Parameters
Returns
public Bitmap copy (Bitmap.Config config, boolean isMutable)Tries to make a new bitmap based on the dimensions of this bitmap, setting the new bitmap’s config to the one specified, and then copying this bitmap’s pixels into the new bitmap. If the conversion is not supported, or the allocator fails, then this returns NULL. The returned bitmap initially has the same density as the original. Parameters
Returns
public void copyPixelsFromBuffer (Buffer src)Copy the pixels from the buffer, beginning at the current position, overwriting the bitmap’s pixels. The data in the buffer is not changed in any way (unlike setPixels(), which converts from unpremultipled 32bit to whatever the bitmap’s native format is. After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements read from the buffer. If you need to read the bitmap from the buffer again you must first rewind the buffer. public void copyPixelsToBuffer (Buffer dst)Copy the bitmap’s pixels into the specified buffer (allocated by the caller). An exception is thrown if the buffer is not large enough to hold all of the pixels (taking into account the number of bytes per pixel) or if the Buffer subclass is not one of the support types (ByteBuffer, ShortBuffer, IntBuffer). The content of the bitmap is copied into the buffer as-is. This means that if this bitmap stores its pixels pre-multiplied (see isPremultiplied() , the values in the buffer will also be pre-multiplied. After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. public static Bitmap createBitmap (DisplayMetrics display, int[] colors, int width, int height, Bitmap.Config config)Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is determined from the given DisplayMetrics . Parameters
Throws
Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is determined from the given DisplayMetrics . Parameters
Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap. Parameters
Returns
Throws
Returns an immutable bitmap from the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap. public static Bitmap createBitmap (DisplayMetrics display, int width, int height, Bitmap.Config config)Returns a mutable bitmap with the specified width and height. Its initial density is determined from the given DisplayMetrics . Parameters
Throws
Returns an immutable bitmap from subset of the source bitmap, transformed by the optional matrix. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap. If the source bitmap is immutable and the requested subset is the same as the source bitmap itself, then the source bitmap is returned and no new bitmap is created. Parameters
Returns
Throws
Returns a mutable bitmap with the specified width and height. Its initial density is as per getDensity() . Parameters
Throws
Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is as per getDensity() . Parameters
Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array. Its initial density is as per getDensity() . Parameters
Throws
Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified width and height are the same as the current width and height of the source bitmap, the source bitmap is returned and no new bitmap is created. Parameters
Returns
Throws
No special parcel contents. Returns
public void eraseColor (int c)Fills the bitmap’s pixels with the specified Color . Throwspublic Bitmap extractAlpha ()Returns a new bitmap that captures the alpha values of the original. This may be drawn with Canvas.drawBitmap(), where the color(s) will be taken from the paint that is passed to the draw call. Returns
public Bitmap extractAlpha (Paint paint, int[] offsetXY)Returns a new bitmap that captures the alpha values of the original. These values may be affected by the optional Paint parameter, which can contain its own alpha, and may also contain a MaskFilter which could change the actual dimensions of the resulting bitmap (e.g. a blur maskfilter might enlarge the resulting bitmap). If offsetXY is not null, it returns the amount to offset the returned bitmap so that it will logically align with the original. For example, if the paint contains a blur of radius 2, then offsetXY[] would contains -2, -2, so that drawing the alpha bitmap offset by (-2, -2) and then drawing the original would result in the blur visually aligning with the original. The initial density of the returned bitmap is the same as the original’s. Parameters
Returns
public final int getAllocationByteCount ()Returns the size of the allocated memory used to store this bitmap’s pixels. This can be larger than the result of getByteCount() if a bitmap is reused to decode other bitmaps of smaller size, or by manual reconfiguration. See reconfigure(int, int, Config) , setWidth(int) , setHeight(int) , setConfig(Bitmap.Config) , and BitmapFactory.Options.inBitmap . If a bitmap is not modified in this way, this value will be the same as that returned by getByteCount() . This value will not change over the lifetime of a Bitmap. See Alsopublic final int getByteCount ()Returns the minimum number of bytes that can be used to store this bitmap’s pixels. As of KITKAT , the result of this method can no longer be used to determine memory usage of a bitmap. See getAllocationByteCount() . public final Bitmap.Config getConfig ()If the bitmap’s internal config is in one of the public formats, return that config, otherwise return null. public int getDensity ()Returns the density for this bitmap. The default density is the same density as the current display, unless the current application does not support different screen densities in which case it is DENSITY_DEFAULT . Note that compatibility mode is determined by the application that was initially loaded into a process — applications that share the same process should all have the same compatibility, or ensure they explicitly set the density of their bitmaps appropriately. Returns
See Alsopublic int getGenerationId ()Returns the generation ID of this bitmap. The generation ID changes whenever the bitmap is modified. This can be used as an efficient way to check if a bitmap has changed. Returns
public final int getHeight ()Returns the bitmap’s height public byte[] getNinePatchChunk ()Returns an optional array of private data, used by the UI system for some bitmaps. Not intended to be called by applications. public int getPixel (int x, int y)Returns the Color at the specified location. Throws an exception if x or y are out of bounds (negative or >= to the width or height respectively). The returned color is a non-premultiplied ARGB value. Parameters
Returns
Throws
public void getPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height)Returns in pixels[] a copy of the data in the bitmap. Each value is a packed int representing a Color . The stride parameter allows the caller to allow for gaps in the returned pixels array between rows. For normal packed results, just pass width for the stride value. The returned colors are non-premultiplied ARGB values. Parameters
Throws
Return the number of bytes between rows in the bitmap’s pixels. Note that this refers to the pixels as stored natively by the bitmap. If you call getPixels() or setPixels(), then the pixels are uniformly treated as 32bit values, packed according to the Color class. As of KITKAT , this method should not be used to calculate the memory usage of the bitmap. Instead, see getAllocationByteCount() . Returns
public int getScaledHeight (DisplayMetrics metrics)Convenience for calling getScaledHeight(int) with the target density of the given DisplayMetrics . public int getScaledHeight (int targetDensity)Convenience method that returns the height of this bitmap divided by the density scale factor. Parameters
Returns
public int getScaledHeight (Canvas canvas)Convenience for calling getScaledHeight(int) with the target density of the given Canvas . public int getScaledWidth (int targetDensity)Convenience method that returns the width of this bitmap divided by the density scale factor. Parameters
Returns
public int getScaledWidth (DisplayMetrics metrics)Convenience for calling getScaledWidth(int) with the target density of the given DisplayMetrics . public int getScaledWidth (Canvas canvas)Convenience for calling getScaledWidth(int) with the target density of the given Canvas . public final int getWidth ()Returns the bitmap’s width public final boolean hasAlpha ()Returns true if the bitmap’s config supports per-pixel alpha, and if the pixels may contain non-opaque alpha values. For some configs, this is always false (e.g. RGB_565), since they do not support per-pixel alpha. However, for configs that do, the bitmap may be flagged to be known that all of its pixels are opaque. In this case hasAlpha() will also return false. If a config such as ARGB_8888 is not so flagged, it will return true by default. public final boolean hasMipMap ()Indicates whether the renderer responsible for drawing this bitmap should attempt to use mipmaps when this bitmap is drawn scaled down. If you know that you are going to draw this bitmap at less than 50% of its original size, you may be able to obtain a higher quality This property is only a suggestion that can be ignored by the renderer. It is not guaranteed to have any effect. Returns
See Alsopublic final boolean isMutable ()Returns true if the bitmap is marked as mutable (i.e. can be drawn into) public final boolean isPremultiplied ()Indicates whether pixels stored in this bitmaps are stored pre-multiplied. When a pixel is pre-multiplied, the RGB components have been multiplied by the alpha component. For instance, if the original color is a 50% translucent red (128, 255, 0, 0) , the pre-multiplied form is (128, 128, 0, 0) . This method always returns false if getConfig() is RGB_565 . The return value is undefined if getConfig() is ALPHA_8 . This method only returns true if hasAlpha() returns true. A bitmap with no alpha channel can be used both as a pre-multiplied and as a non pre-multiplied bitmap. Only pre-multiplied bitmaps may be drawn by the view system or Canvas . If a non-pre-multiplied bitmap with an alpha channel is drawn to a Canvas, a RuntimeException will be thrown. Returns
See Alsopublic final boolean isRecycled ()Returns true if this bitmap has been recycled. If so, then it is an error to try to access its pixels, and the bitmap will not draw. Returns
public void prepareToDraw ()Rebuilds any caches associated with the bitmap that are used for drawing it. In the case of purgeable bitmaps, this call will attempt to ensure that the pixels have been decoded. If this is called on more than one bitmap in sequence, the priority is given in LRU order (i.e. the last bitmap called will be given highest priority). For bitmaps with no associated caches, this call is effectively a no-op, and therefore is harmless. public void reconfigure (int width, int height, Bitmap.Config config)Modifies the bitmap to have a specified width, height, and Bitmap.Config , without affecting the underlying allocation backing the bitmap. Bitmap pixel data is not re-initialized for the new configuration. This method can be used to avoid allocating a new bitmap, instead reusing an existing bitmap’s allocation for a new configuration of equal or lesser size. If the Bitmap’s allocation isn’t large enough to support the new configuration, an IllegalArgumentException will be thrown and the bitmap will not be modified. The result of getByteCount() will reflect the new configuration, while getAllocationByteCount() will reflect that of the initial configuration. Note: This may change this result of hasAlpha(). When converting to 565, the new bitmap will always be considered opaque. When converting from 565, the new bitmap will be considered non-opaque, and will respect the value set by setPremultiplied(). WARNING: This method should NOT be called on a bitmap currently used by the view system. It does not make guarantees about how the underlying pixel buffer is remapped to the new config, just that the allocation is reused. Additionally, the view system does not account for bitmap properties being modifying during use, e.g. while attached to drawables. See Alsopublic void recycle ()Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as «dead», meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap. public boolean sameAs (Bitmap other)Given another bitmap, return true if it has the same dimensions, config, and pixel data as this bitmap. If any of those differ, return false. If other is null, return false. public void setConfig (Bitmap.Config config)Convenience method for calling reconfigure(int, int, Config) with the current height and width. WARNING: this method should not be used on bitmaps currently used by the view system, see reconfigure(int, int, Config) for more details. See Alsopublic void setDensity (int density)Specifies the density for this bitmap. When the bitmap is drawn to a Canvas that also has a density, it will be scaled appropriately. Parameters
See Alsopublic void setHasAlpha (boolean hasAlpha)Tell the bitmap if all of the pixels are known to be opaque (false) or if some of the pixels may contain non-opaque alpha values (true). Note, for some configs (e.g. RGB_565) this call is ignored, since it does not support per-pixel alpha values. This is meant as a drawing hint, as in some cases a bitmap that is known to be opaque can take a faster drawing case than one that may have non-opaque per-pixel alpha values. public final void setHasMipMap (boolean hasMipMap)Set a hint for the renderer responsible for drawing this bitmap indicating that it should attempt to use mipmaps when this bitmap is drawn scaled down. If you know that you are going to draw this bitmap at less than 50% of its original size, you may be able to obtain a higher quality by turning this property on. Note that if the renderer respects this hint it might have to allocate extra memory to hold the mipmap levels for this bitmap. This property is only a suggestion that can be ignored by the renderer. It is not guaranteed to have any effect. Источник |
---|