-
- All Implemented Interfaces:
-
android.graphics.drawable.Animatable
,android.widget.MediaController.MediaPlayerControl
public class GifDrawable extends Drawable implements Animatable, MediaController.MediaPlayerControl
A Drawable which can be used to hold GIF images, especially animations. Basic GIF metadata can also be examined.
-
-
Constructor Summary
Constructors Constructor Description GifDrawable(Resources res, int id)
Creates drawable from resource. GifDrawable(AssetManager assets, String assetName)
Creates drawable from asset. GifDrawable(String filePath)
Constructs drawable from given file path. GifDrawable(File file)
Equivalent to {@code}
GifDrawable(file.GifDrawable(InputStream stream)
Creates drawable from InputStream.InputStream must support marking, IllegalArgumentException will be thrown otherwise. GifDrawable(AssetFileDescriptor afd)
Creates drawable from AssetFileDescriptor. GifDrawable(FileDescriptor fd)
Creates drawable from FileDescriptor GifDrawable(Array<byte> bytes)
Creates drawable from byte array. GifDrawable(ByteBuffer buffer)
Creates drawable from ByteBuffer. GifDrawable(ContentResolver resolver, Uri uri)
Creates drawable from android.net.Uri which is resolved using {@code resolver}
.
-
Method Summary
Modifier and Type Method Description void
recycle()
Frees any memory allocated native way.Operation is irreversible. boolean
isRecycled()
void
invalidateSelf()
int
getIntrinsicHeight()
int
getIntrinsicWidth()
void
setAlpha(@IntRange(from = 0, to = 255) int alpha)
void
setColorFilter(@Nullable() ColorFilter cf)
int
getOpacity()
See getOpacity void
start()
Starts the animation. void
reset()
Causes the animation to start over.If rewinding input source fails then state is not affected.This method is thread-safe. void
stop()
Stops the animation. boolean
isRunning()
String
getComment()
Returns GIF comment int
getLoopCount()
Returns loop count previously read from GIF's application extension block.Defaults to 1 if there is no such extension. void
setLoopCount(@IntRange(from = 0, to = Character.MAX_VALUE) int loopCount)
Sets loop count of the animation. String
toString()
int
getNumberOfFrames()
GifError
getError()
Retrieves last error which is also the indicator of current GIF status. static GifDrawable
createFromResource(@NonNull() Resources res, @RawRes() @DrawableRes() int resourceId)
An GifDrawable wrapper but returns nullinstead of throwing exception if creation fails. void
setSpeed(@FloatRange(from = 0, fromInclusive = false) float factor)
Sets new animation speed factor. void
pause()
Equivalent of stop int
getDuration()
Retrieves duration of one loop of the animation.If there is no data (no Graphics Control Extension blocks) 0 is returned. int
getCurrentPosition()
Retrieves elapsed time from the beginning of a current loop of animation.If there is only 1 frame or drawable is recycled 0 is returned. void
seekTo(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Seeks animation to given absolute position (within given loop) and refreshes the canvas. void
seekToBlocking(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Like seekTo but performs operation synchronously on current thread void
seekToFrame(@IntRange(from = 0, to = Integer.MAX_VALUE) int frameIndex)
Like seekTo but uses index of the frame instead of time. Bitmap
seekToFrameAndGet(@IntRange(from = 0, to = Integer.MAX_VALUE) int frameIndex)
Like seekToFrame but performs operation synchronously and returns that frame. Bitmap
seekToPositionAndGet(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Like seekTo but performs operation synchronously and returns that frame. boolean
isPlaying()
Equivalent of isRunning int
getBufferPercentage()
Used by MediaPlayer for secondary progress bars.There is no buffer in GifDrawable, so buffer is assumed to be always full. boolean
canPause()
Checks whether pause is supported. boolean
canSeekBackward()
Checks whether seeking backward can be performed. boolean
canSeekForward()
Checks whether seeking forward can be performed. int
getAudioSessionId()
Used by MediaPlayer.GIFs contain no sound, so 0 is always returned. int
getFrameByteCount()
Returns the minimum number of bytes that can be used to store pixels of the single frame.Returned value is the same for all the frames since it is based on the size of GIF screen. long
getAllocationByteCount()
Returns size of the memory needed to store pixels of this object. long
getMetadataAllocationByteCount()
Returns the maximum possible size of the allocated memory used to store pixels and metadata of this object.It counts length of all frame buffers. long
getInputSourceByteCount()
Returns length of the input source obtained at the opening time or -1 iflength cannot be determined. void
getPixels(@NonNull() Array<int> pixels)
Returns in pixels[] a copy of the data in the current frame. int
getPixel(@IntRange(from = 0) int x, @IntRange(from = 0) int y)
Returns the Color at the specified location. void
draw(@NonNull() Canvas canvas)
Reads and renders new frame if needed then draws last rendered frame. final Paint
getPaint()
int
getAlpha()
void
setFilterBitmap(boolean filter)
void
setDither(boolean dither)
void
addAnimationListener(@NonNull() AnimationListener listener)
Adds a new animation listener boolean
removeAnimationListener(AnimationListener listener)
Removes an animation listener ColorFilter
getColorFilter()
Bitmap
getCurrentFrame()
Retrieves a copy of currently buffered frame. void
setTintList(ColorStateList tint)
void
setTintMode(@Nullable() PorterDuff.Mode tintMode)
boolean
isStateful()
boolean
setVisible(boolean visible, boolean restart)
Sets whether this drawable is visible. int
getCurrentFrameIndex()
Returns zero-based index of recently rendered frame in given loop or -1 when drawable is recycled. int
getCurrentLoop()
Returns zero-based index of currently played animation loop. boolean
isAnimationCompleted()
Returns whether all animation loops has ended. int
getFrameDuration(@IntRange(from = 0) int index)
Returns duration of the given frame (in milliseconds). void
setCornerRadius(@FloatRange(from = 0) float cornerRadius)
Sets the corner radius to be applied when drawing the bitmap. float
getCornerRadius()
void
setTransform(@Nullable() Transform transform)
Specify a Transform implementation to customize how the GIF's current Bitmap is drawn. Transform
getTransform()
-
Methods inherited from class android.graphics.drawable.Drawable
applyTheme, canApplyTheme, clearColorFilter, copyBounds, copyBounds, createFromPath, createFromResourceStream, createFromStream, createFromXml, createFromXmlInner, draw, getAlpha, getBounds, getCallback, getChangingConfigurations, getColorFilter, getConstantState, getCurrent, getDirtyBounds, getHotspotBounds, getIntrinsicHeight, getIntrinsicWidth, getLayoutDirection, getLevel, getMinimumHeight, getMinimumWidth, getOpacity, getOpticalInsets, getOutline, getPadding, getState, getTransparentRegion, hasFocusStateSpecified, inflate, invalidateSelf, isAutoMirrored, isFilterBitmap, isProjected, isStateful, isVisible, jumpToCurrentState, mutate, onLayoutDirectionChanged, resolveOpacity, scheduleSelf, setAlpha, setAutoMirrored, setBounds, setCallback, setChangingConfigurations, setColorFilter, setDither, setFilterBitmap, setHotspot, setHotspotBounds, setLayoutDirection, setLevel, setState, setTint, setTintBlendMode, setTintList, setTintMode, setVisible, unscheduleSelf
-
Methods inherited from class android.graphics.drawable.Animatable
isRunning, start, stop
-
Methods inherited from class android.widget.MediaController.MediaPlayerControl
canPause, canSeekBackward, canSeekForward, getAudioSessionId, getBufferPercentage, getCurrentPosition, getDuration, isPlaying, pause, seekTo
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Constructor Detail
-
GifDrawable
GifDrawable(Resources res, int id)
Creates drawable from resource.- Parameters:
res
- Resources to read fromid
- resource id (raw or drawable)
-
GifDrawable
GifDrawable(AssetManager assets, String assetName)
Creates drawable from asset.- Parameters:
assets
- AssetManager to read fromassetName
- name of the asset
-
GifDrawable
GifDrawable(String filePath)
Constructs drawable from given file path.- Parameters:
filePath
- path to the GIF file
-
GifDrawable
GifDrawable(File file)
Equivalent to{@code}
GifDrawable(file.- Parameters:
file
- the GIF file
-
GifDrawable
GifDrawable(InputStream stream)
Creates drawable from InputStream.InputStream must support marking, IllegalArgumentException will be thrown otherwise.- Parameters:
stream
- stream to read from
-
GifDrawable
GifDrawable(AssetFileDescriptor afd)
Creates drawable from AssetFileDescriptor.- Parameters:
afd
- source
-
GifDrawable
GifDrawable(FileDescriptor fd)
Creates drawable from FileDescriptor- Parameters:
fd
- source
-
GifDrawable
GifDrawable(Array<byte> bytes)
Creates drawable from byte array.- Parameters:
bytes
- raw GIF bytes
-
GifDrawable
GifDrawable(ByteBuffer buffer)
Creates drawable from ByteBuffer.- Parameters:
buffer
- buffer containing GIF data
-
GifDrawable
GifDrawable(ContentResolver resolver, Uri uri)
Creates drawable from android.net.Uri which is resolved using{@code resolver}
.- Parameters:
resolver
- resolver used to query{@code uri}
, can be null for file:// scheme Urisuri
- GIF Uri, cannot be null.
-
-
Method Detail
-
recycle
void recycle()
Frees any memory allocated native way.Operation is irreversible. After this call, nothing will be drawn.This method is idempotent, subsequent calls have no effect.Like recycle this is an advanced call andis invoked implicitly by finalizer.
-
isRecycled
boolean isRecycled()
-
invalidateSelf
void invalidateSelf()
-
getIntrinsicHeight
int getIntrinsicHeight()
-
getIntrinsicWidth
int getIntrinsicWidth()
-
setColorFilter
void setColorFilter(@Nullable() ColorFilter cf)
-
getOpacity
int getOpacity()
See getOpacity
-
start
void start()
Starts the animation. Does nothing if GIF is not animated.This method is thread-safe.
-
reset
void reset()
Causes the animation to start over.If rewinding input source fails then state is not affected.This method is thread-safe.
-
stop
void stop()
Stops the animation. Does nothing if GIF is not animated.This method is thread-safe.
-
isRunning
boolean isRunning()
-
getComment
@Nullable() String getComment()
Returns GIF comment
-
getLoopCount
int getLoopCount()
Returns loop count previously read from GIF's application extension block.Defaults to 1 if there is no such extension.
-
setLoopCount
void setLoopCount(@IntRange(from = 0, to = Character.MAX_VALUE) int loopCount)
Sets loop count of the animation. Loop count must be in range
{@code <0 ,65535>}
- Parameters:
loopCount
- loop count, 0 means infinity
-
getNumberOfFrames
int getNumberOfFrames()
-
getError
@NonNull() GifError getError()
Retrieves last error which is also the indicator of current GIF status.
-
createFromResource
@Nullable() static GifDrawable createFromResource(@NonNull() Resources res, @RawRes() @DrawableRes() int resourceId)
An GifDrawable wrapper but returns nullinstead of throwing exception if creation fails.
- Parameters:
res
- resources to read fromresourceId
- resource id
-
setSpeed
void setSpeed(@FloatRange(from = 0, fromInclusive = false) float factor)
Sets new animation speed factor.Note: If animation is in progress (draw) was already called)then effects will be visible starting from the next frame. Duration of the currently renderedframe is not affected.
- Parameters:
factor
- new speed factor, eg.
-
getDuration
int getDuration()
Retrieves duration of one loop of the animation.If there is no data (no Graphics Control Extension blocks) 0 is returned.Note that one-frame GIFs can have non-zero duration defined in Graphics Control Extension block,use getNumberOfFrames to determine if there is one or more frames.
-
getCurrentPosition
int getCurrentPosition()
Retrieves elapsed time from the beginning of a current loop of animation.If there is only 1 frame or drawable is recycled 0 is returned.
-
seekTo
void seekTo(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Seeks animation to given absolute position (within given loop) and refreshes the canvas.If
position
is greater than duration of the loop of animation (or whole animation if there is no loop)then animation will be sought to the end, no exception will be thrown.NOTE: all frames from current (or first one if seeking backward) to desired one must be rendered sequentially to perform seeking.It may take a lot of time if number of such frames is large.Method is thread-safe. Decoding is performed in background thread and drawable is invalidated automaticallyafterwards.- Parameters:
position
- position to seek to in milliseconds
-
seekToBlocking
void seekToBlocking(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Like seekTo but performs operation synchronously on current thread
- Parameters:
position
- position to seek to in milliseconds
-
seekToFrame
void seekToFrame(@IntRange(from = 0, to = Integer.MAX_VALUE) int frameIndex)
Like seekTo but uses index of the frame instead of time.If
frameIndex
exceeds number of frames, seek stops at the end, no exception is thrown.- Parameters:
frameIndex
- index of the frame to seek to (zero based)
-
seekToFrameAndGet
Bitmap seekToFrameAndGet(@IntRange(from = 0, to = Integer.MAX_VALUE) int frameIndex)
Like seekToFrame but performs operation synchronously and returns that frame.
- Parameters:
frameIndex
- index of the frame to seek to (zero based)
-
seekToPositionAndGet
Bitmap seekToPositionAndGet(@IntRange(from = 0, to = Integer.MAX_VALUE) int position)
Like seekTo but performs operation synchronously and returns that frame.
- Parameters:
position
- position to seek to in milliseconds
-
getBufferPercentage
int getBufferPercentage()
Used by MediaPlayer for secondary progress bars.There is no buffer in GifDrawable, so buffer is assumed to be always full.
-
canPause
boolean canPause()
Checks whether pause is supported.
-
canSeekBackward
boolean canSeekBackward()
Checks whether seeking backward can be performed.
-
canSeekForward
boolean canSeekForward()
Checks whether seeking forward can be performed.
-
getAudioSessionId
int getAudioSessionId()
Used by MediaPlayer.GIFs contain no sound, so 0 is always returned.
-
getFrameByteCount
int getFrameByteCount()
Returns the minimum number of bytes that can be used to store pixels of the single frame.Returned value is the same for all the frames since it is based on the size of GIF screen.
This method should not be used to calculate the memory usage of the bitmap.Instead see getAllocationByteCount.
-
getAllocationByteCount
long getAllocationByteCount()
Returns size of the memory needed to store pixels of this object. It counts possible length of all frame buffers.Returned value may be lower than amount of actually allocated memory if GIF uses dispose to previous method but frame requiring ithas never been needed yet. Returned value does not change during runtime.
-
getMetadataAllocationByteCount
long getMetadataAllocationByteCount()
Returns the maximum possible size of the allocated memory used to store pixels and metadata of this object.It counts length of all frame buffers. Returned value does not change over time.
-
getInputSourceByteCount
long getInputSourceByteCount()
Returns length of the input source obtained at the opening time or -1 iflength cannot be determined. Returned value does not change during runtime.If GifDrawable is constructed from InputStream -1 is always returned.In case of byte array and ByteBuffer length is always known.In other cases length -1 can be returned if length cannot be determined.
-
getPixels
void getPixels(@NonNull() Array<int> pixels)
Returns in pixels[] a copy of the data in the current frame. Each value is a packed int representing a Color.
- Parameters:
pixels
- the array to receive the frame's colors
-
getPixel
int getPixel(@IntRange(from = 0) int x, @IntRange(from = 0) int y)
Returns the Color at the specified location. Throws an exceptionif x or y are out of bounds (negative or >= to the width or heightrespectively). The returned color is a non-premultiplied ARGB value.
- Parameters:
x
- The x coordinate (0...y
- The y coordinate (0...
-
draw
void draw(@NonNull() Canvas canvas)
Reads and renders new frame if needed then draws last rendered frame.
- Parameters:
canvas
- canvas to draw into
-
getAlpha
int getAlpha()
-
setFilterBitmap
void setFilterBitmap(boolean filter)
-
setDither
void setDither(boolean dither)
-
addAnimationListener
void addAnimationListener(@NonNull() AnimationListener listener)
Adds a new animation listener
- Parameters:
listener
- animation listener to be added, not null
-
removeAnimationListener
boolean removeAnimationListener(AnimationListener listener)
Removes an animation listener
- Parameters:
listener
- animation listener to be removed
-
getColorFilter
ColorFilter getColorFilter()
-
getCurrentFrame
Bitmap getCurrentFrame()
Retrieves a copy of currently buffered frame.
-
setTintList
void setTintList(ColorStateList tint)
-
setTintMode
void setTintMode(@Nullable() PorterDuff.Mode tintMode)
-
isStateful
boolean isStateful()
-
setVisible
boolean setVisible(boolean visible, boolean restart)
Sets whether this drawable is visible. If rendering of next frame is scheduled on draw current one (the default) then this methodonly calls through to the super class's implementation.Otherwise (if setRenderingTriggeredOnDraw was used with
true
)when the drawable becomes invisible, it will pause its animation. Asubsequent change to visible withrestart
set to true willrestart the animation from the first frame. Ifrestart
isfalse, the animation will resume from the most recent frame.- Parameters:
visible
- true if visible, false otherwiserestart
- when visible and rendering is triggered on draw, true to force the animation to restartfrom the first frame
-
getCurrentFrameIndex
int getCurrentFrameIndex()
Returns zero-based index of recently rendered frame in given loop or -1 when drawable is recycled.
-
getCurrentLoop
int getCurrentLoop()
Returns zero-based index of currently played animation loop. If animation is infinite ordrawable is recycled 0 is returned.
-
isAnimationCompleted
boolean isAnimationCompleted()
Returns whether all animation loops has ended. If drawable is recycled false is returned.
-
getFrameDuration
int getFrameDuration(@IntRange(from = 0) int index)
Returns duration of the given frame (in milliseconds). If there is no data (no GraphicsControl Extension blocks or drawable is recycled) 0 is returned.
- Parameters:
index
- index of the frame
-
setCornerRadius
void setCornerRadius(@FloatRange(from = 0) float cornerRadius)
Sets the corner radius to be applied when drawing the bitmap.Note that changing corner radius will cause replacing current Paint shader by BitmapShader.Transform set by setTransform will also be replaced.
- Parameters:
cornerRadius
- corner radius or 0 to remove rounding
-
getCornerRadius
@FloatRange(from = 0) float getCornerRadius()
-
setTransform
void setTransform(@Nullable() Transform transform)
Specify a Transform implementation to customize how the GIF's current Bitmap is drawn.
- Parameters:
transform
- new Transform or null to remove current one
-
getTransform
@Nullable() Transform getTransform()
-
-
-
-