### Implement GifTextureView for Hardware Accelerated Rendering Source: https://context7.com/koral--/android-gif-drawable/llms.txt Shows how to use GifTextureView for performance-critical GIF rendering. Includes examples for setting input sources from resources, assets, or files, and configuring scale types and transformations. ```xml ``` ```java GifTextureView gifTextureView = new GifTextureView(context); InputSource source = new InputSource.ResourcesSource(getResources(), R.drawable.animation); gifTextureView.setInputSource(source); gifTextureView.setSpeed(2.0f); gifTextureView.setScaleType(ImageView.ScaleType.FIT_CENTER); gifTextureView.setFreezesAnimation(true); ``` -------------------------------- ### Gradle Setup for Android GIF Drawable Source: https://context7.com/koral--/android-gif-drawable/llms.txt Instructions on how to add the Android GIF Drawable library dependency to your project's build.gradle file and configure necessary repositories. ```groovy // In your app's build.gradle dependencies { implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.31' } // In your project's build.gradle or settings.gradle (for repository) repositories { mavenCentral() } // For snapshot versions (development builds) repositories { mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } } dependencies { implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.+' } ``` -------------------------------- ### Android GIF Drawable InputSource Examples Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates various ways to create an InputSource for GIF data, including from resources, assets, files, byte arrays, direct ByteBuffers, Uris, FileDescriptors, InputStreams, and AssetFileDescriptors. Also shows basic usage with GifTextureView, GifDecoder, and GifTexImage2D. ```java InputSource resourceSource = new InputSource.ResourcesSource(getResources(), R.drawable.animation); InputSource assetSource = new InputSource.AssetSource(getAssets(), "animations/loading.gif"); InputSource fileSource = new InputSource.FileSource("/sdcard/Download/animation.gif"); InputSource fileObjSource = new InputSource.FileSource(new File(getFilesDir(), "animation.gif")); byte[] gifData = downloadGifData(); InputSource byteSource = new InputSource.ByteArraySource(gifData); ByteBuffer directBuffer = ByteBuffer.allocateDirect(gifData.length); directBuffer.put(gifData); directBuffer.rewind(); InputSource bufferSource = new InputSource.DirectByteBufferSource(directBuffer); Uri contentUri = Uri.parse("content://media/external/images/media/123"); InputSource uriSource = new InputSource.UriSource(getContentResolver(), contentUri); Uri fileUri = Uri.parse("file:///sdcard/animation.gif"); InputSource fileUriSource = new InputSource.UriSource(null, fileUri); FileDescriptor fd = new RandomAccessFile("/sdcard/animation.gif", "r").getFD(); InputSource fdSource = new InputSource.FileDescriptorSource(fd); InputStream stream = openInputStream(); InputSource streamSource = new InputSource.InputStreamSource(stream); AssetFileDescriptor afd = getAssets().openFd("animation.gif"); InputSource afdSource = new InputSource.AssetFileDescriptorSource(afd); GifTextureView textureView = findViewById(R.id.gif_texture_view); textureView.setInputSource(resourceSource); GifDecoder decoder = new GifDecoder(byteSource); GifTexImage2D texture = new GifTexImage2D(fileSource, null); ``` -------------------------------- ### MultiCallback - Sharing GifDrawable Across Views Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates how to use MultiCallback to display and animate a single GifDrawable across multiple Views simultaneously, including setup for ImageViews and ImageSpans in TextViews. ```APIDOC ## MultiCallback - Sharing GifDrawable Across Views MultiCallback allows a single GifDrawable to be displayed and animated across multiple Views simultaneously. ### Description This section shows how to create a shared `GifDrawable` and use `MultiCallback` to attach it to multiple `ImageView` instances. It also covers using `MultiCallback` with `ImageSpan` in `TextView` for inline GIF display. ### Usage 1. Create a `GifDrawable`. 2. Create a `MultiCallback` instance. 3. Set the `GifDrawable` on your Views (e.g., `ImageView`, `TextView` with `ImageSpan`). 4. Add each View to the `MultiCallback` using `addView()`. 5. Set the `MultiCallback` as the callback for the `GifDrawable` using `setCallback()`. 6. For `TextView` with `ImageSpan`, initialize `MultiCallback` with `useViewInvalidate = true`. 7. Remember to remove views from the callback when they are no longer needed using `removeView()`. 8. If the drawable on a view changes and then reverts to the shared drawable, re-add the view to the callback and re-set the callback on the drawable. ### Code Example ```java // Create a GifDrawable to share GifDrawable sharedGifDrawable = new GifDrawable(getResources(), R.drawable.animation); // Create MultiCallback MultiCallback multiCallback = new MultiCallback(); // Set up first ImageView ImageView imageView1 = findViewById(R.id.image_view_1); imageView1.setImageDrawable(sharedGifDrawable); multiCallback.addView(imageView1); // Set up second ImageView with the same drawable ImageView imageView2 = findViewById(R.id.image_view_2); imageView2.setImageDrawable(sharedGifDrawable); multiCallback.addView(imageView2); // Set callback on the drawable sharedGifDrawable.setCallback(multiCallback); // For ImageSpan in TextView, use view invalidation mode MultiCallback spanCallback = new MultiCallback(true); // useViewInvalidate = true TextView textView = findViewById(R.id.text_view); SpannableString spannable = new SpannableString("Text with GIF "); ImageSpan imageSpan = new ImageSpan(sharedGifDrawable); spannable.setSpan(imageSpan, spannable.length() - 1, spannable.length(), 0); textView.setText(spannable); spanCallback.addView(textView); sharedGifDrawable.setCallback(spanCallback); // Remove view when no longer displaying multiCallback.removeView(imageView1); // Important: If drawable is changed on a view, reassign callback imageView1.setImageDrawable(anotherDrawable); // After setting back to shared drawable, re-add to callback imageView1.setImageDrawable(sharedGifDrawable); multiCallback.addView(imageView1); sharedGifDrawable.setCallback(multiCallback); ``` ``` -------------------------------- ### Gradle Dependency Setup for Android GIF Drawable Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md This snippet shows how to add the android-gif-drawable library to your Android project using Gradle. It includes the standard dependency and repository configurations for both stable releases and development snapshots. ```groovy dependencies { implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.31' } repositories { mavenCentral() } // For snapshot repository: // repositories { // mavenCentral() // maven { url "https://oss.sonatype.org/content/repositories/snapshots" } // } // dependencies { // implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.+' // } ``` -------------------------------- ### GifTextView - Compound Drawable GIFs Source: https://context7.com/koral--/android-gif-drawable/llms.txt GifTextView extends TextView to support animated GIFs as compound drawables (left, top, right, bottom, start, end) and background. It allows for easy integration of animated GIFs within text views. ```APIDOC ## GifTextView - Compound Drawable GIFs GifTextView extends TextView to support animated GIFs as compound drawables (left, top, right, bottom, start, end) and background. ### XML Usage ```xml ``` ### Programmatic Usage ```java // Programmatic creation GifTextView gifTextView = new GifTextView(context); gifTextView.setText("Animated Text"); // Set compound drawables programmatically gifTextView.setCompoundDrawablesWithIntrinsicBounds( R.drawable.left_animation, // left R.drawable.top_animation, // top R.drawable.right_animation, // right 0 // bottom (none) ); // Set relative compound drawables (start/end for RTL support) gifTextView.setCompoundDrawablesRelativeWithIntrinsicBounds( R.drawable.start_animation, // start 0, // top R.drawable.end_animation, // end 0 // bottom ); // Set animated background gifTextView.setBackgroundResource(R.drawable.animated_background); // Preserve animation state across configuration changes gifTextView.setFreezesAnimation(true); ``` ``` -------------------------------- ### Control GifDrawable Animation in Java Source: https://context7.com/koral--/android-gif-drawable/llms.txt Explains how to control the animation of a GifDrawable using methods like start, stop, pause, reset, seekTo, and setSpeed. It also covers retrieving animation state such as current position, frame index, loop count, and completion status. ```java GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.animation); gifDrawable.start(); gifDrawable.stop(); boolean isRunning = gifDrawable.isRunning(); boolean isPlaying = gifDrawable.isPlaying(); gifDrawable.reset(); gifDrawable.setSpeed(2.0f); gifDrawable.seekTo(1500); gifDrawable.seekToBlocking(1500); gifDrawable.seekToFrame(5); Bitmap frame = gifDrawable.seekToFrameAndGet(5); Bitmap frameAtTime = gifDrawable.seekToPositionAndGet(1500); int currentPosition = gifDrawable.getCurrentPosition(); int currentFrameIndex = gifDrawable.getCurrentFrameIndex(); int currentLoop = gifDrawable.getCurrentLoop(); boolean completed = gifDrawable.isAnimationCompleted(); gifDrawable.setLoopCount(3); int loopCount = gifDrawable.getLoopCount(); ``` -------------------------------- ### Implementing GifImageView in Android Source: https://context7.com/koral--/android-gif-drawable/llms.txt Shows how to integrate GifImageView as a drop-in replacement for standard ImageViews. Includes both XML layout configuration and programmatic control for playback and state management. ```xml ``` ```java GifImageView gifImageView = new GifImageView(context); gifImageView.setImageResource(R.drawable.animation); gifImageView.setImageURI(Uri.parse("file:///sdcard/animation.gif")); gifImageView.setBackgroundResource(R.drawable.background_animation); Drawable drawable = gifImageView.getDrawable(); if (drawable instanceof GifDrawable) { GifDrawable gifDrawable = (GifDrawable) drawable; gifDrawable.stop(); gifDrawable.setSpeed(1.5f); } gifImageView.setFreezesAnimation(true); final GifDrawable gifDrawable = (GifDrawable) gifImageView.getDrawable(); MediaController mediaController = new MediaController(this); mediaController.setMediaPlayer(gifDrawable); mediaController.setAnchorView(gifImageView); gifImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaController.show(); } }); ``` -------------------------------- ### Implement GifTextView for Compound Drawables Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates how to use GifTextView to display animated GIFs as compound drawables or backgrounds. It covers both XML layout declaration and programmatic configuration including RTL support. ```xml ``` ```java GifTextView gifTextView = new GifTextView(context); gifTextView.setText("Animated Text"); gifTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.left_animation, R.drawable.top_animation, R.drawable.right_animation, 0); gifTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.start_animation, 0, R.drawable.end_animation, 0); gifTextView.setBackgroundResource(R.drawable.animated_background); gifTextView.setFreezesAnimation(true); ``` -------------------------------- ### GifDrawableBuilder - Fluent API for Construction Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates the fluent builder pattern for constructing GifDrawable objects with options for subsampling, reusing bitmaps, custom thread pools, and advanced configuration. ```APIDOC ## GifDrawableBuilder - Fluent API for Construction PProvides a fluent builder pattern for constructing GifDrawable with various options like sample size, executor, and rendering behavior. ### Basic builder usage with file ```java GifDrawable gif = new GifDrawableBuilder() .from(new File("/sdcard/animation.gif")) .build(); ``` ### Builder with subsampling (reduces memory usage) ```java GifDrawable subsampledGif = new GifDrawableBuilder() .from(getResources(), R.drawable.large_animation) .sampleSize(2) // 1/4 of original pixels .build(); ``` ### Reuse old drawable's bitmap buffer ```java GifDrawable newGif = new GifDrawableBuilder() .from(getAssets(), "new_animation.gif") .with(oldGifDrawable) // Reuse memory from old drawable .build(); ``` ### Custom thread pool for rendering ```java GifDrawable gifWithExecutor = new GifDrawableBuilder() .from(bytes) .threadPoolSize(2) .build(); ``` ### Or use a custom executor ```java ScheduledThreadPoolExecutor customExecutor = new ScheduledThreadPoolExecutor(1); GifDrawable gifWithCustomExecutor = new GifDrawableBuilder() .from(inputStream) .taskExecutor(customExecutor) .build(); ``` ### Control rendering trigger behavior ```java GifDrawable gif = new GifDrawableBuilder() .from(getResources(), R.drawable.anim) .renderingTriggeredOnDraw(false) // Render even when not drawn .build(); ``` ### Use GifOptions for advanced configuration ```java GifOptions options = new GifOptions(); options.setInSampleSize(4); options.setInIsOpaque(true); // Faster if GIF is known to be opaque GifDrawable optimizedGif = new GifDrawableBuilder() .from(filePath) .options(options) .build(); ``` ### Builder from various sources ```java GifDrawable fromUri = new GifDrawableBuilder() .from(getContentResolver(), Uri.parse("content://...")) .build(); GifDrawable fromBuffer = new GifDrawableBuilder() .from(directByteBuffer) .build(); ``` ``` -------------------------------- ### Constructing GifDrawable with Fluent Builder Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates how to use GifDrawableBuilder to create GIF drawables from various sources like files, assets, and buffers. It covers advanced configurations such as subsampling, custom thread pools, and memory reuse. ```java GifDrawable gif = new GifDrawableBuilder().from(new File("/sdcard/animation.gif")).build(); GifDrawable subsampledGif = new GifDrawableBuilder().from(getResources(), R.drawable.large_animation).sampleSize(2).build(); GifDrawable newGif = new GifDrawableBuilder().from(getAssets(), "new_animation.gif").with(oldGifDrawable).build(); GifDrawable gifWithExecutor = new GifDrawableBuilder().from(bytes).threadPoolSize(2).build(); ScheduledThreadPoolExecutor customExecutor = new ScheduledThreadPoolExecutor(1); GifDrawable gifWithCustomExecutor = new GifDrawableBuilder().from(inputStream).taskExecutor(customExecutor).build(); GifDrawable gif = new GifDrawableBuilder().from(getResources(), R.drawable.anim).renderingTriggeredOnDraw(false).build(); GifOptions options = new GifOptions(); options.setInSampleSize(4); options.setInIsOpaque(true); GifDrawable optimizedGif = new GifDrawableBuilder().from(filePath).options(options).build(); GifDrawable fromUri = new GifDrawableBuilder().from(getContentResolver(), Uri.parse("content://...")).build(); GifDrawable fromBuffer = new GifDrawableBuilder().from(directByteBuffer).build(); ``` -------------------------------- ### Integrate Animated GIFs with OpenGL ES using GifTexImage2D Source: https://context7.com/koral--/android-gif-drawable/llms.txt Shows how to render animated GIFs within an OpenGL ES context. It covers texture initialization, automatic decoder thread management, and manual frame control for custom playback. ```java InputSource source = new InputSource.FileSource("/sdcard/animation.gif"); GifTexImage2D gifTexture = new GifTexImage2D(source, new GifOptions()); gifTexture.glTexImage2D(GLES20.GL_TEXTURE_2D, 0); gifTexture.startDecoderThread(); // In render loop: gifTexture.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0); gifTexture.stopDecoderThread(); gifTexture.recycle(); ``` -------------------------------- ### Create GifDrawable Instances in Java Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates various ways to create a GifDrawable object from different data sources like resources, assets, files, byte arrays, streams, and URIs. Includes a safe creation method that returns null on failure. ```java GifDrawable gifFromResource = new GifDrawable(getResources(), R.drawable.anim); GifDrawable gifFromAssets = new GifDrawable(getAssets(), "anim.gif"); GifDrawable gifFromPath = new GifDrawable("/sdcard/anim.gif"); File gifFile = new File(getFilesDir(), "anim.gif"); GifDrawable gifFromFile = new GifDrawable(gifFile); byte[] rawGifBytes = loadGifBytes(); GifDrawable gifFromBytes = new GifDrawable(rawGifBytes); ByteBuffer buffer = ByteBuffer.allocateDirect(gifData.length); buffer.put(gifData); buffer.rewind(); GifDrawable gifFromBuffer = new GifDrawable(buffer); InputStream sourceIs = openGifStream(); BufferedInputStream bis = new BufferedInputStream(sourceIs, gifLength); GifDrawable gifFromStream = new GifDrawable(bis); Uri gifUri = Uri.parse("content://media/external/images/123"); GifDrawable gifFromUri = new GifDrawable(getContentResolver(), gifUri); GifDrawable safeGif = GifDrawable.createFromResource(getResources(), R.drawable.anim); if (safeGif != null) { imageView.setImageDrawable(safeGif); } ``` -------------------------------- ### Instantiate GifDrawable from various sources Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Demonstrates how to create a GifDrawable object from different input sources such as assets, resources, files, byte arrays, and InputStreams. All sources must support rewinding to the beginning for proper animation playback. ```java GifDrawable gifFromAssets = new GifDrawable( getAssets(), "anim.gif" ); GifDrawable gifFromResource = new GifDrawable( getResources(), R.drawable.anim ); ContentResolver contentResolver = ...; GifDrawable gifFromUri = new GifDrawable( contentResolver, gifUri ); byte[] rawGifBytes = ...; GifDrawable gifFromBytes = new GifDrawable( rawGifBytes ); FileDescriptor fd = new RandomAccessFile( "/path/anim.gif", "r" ).getFD(); GifDrawable gifFromFd = new GifDrawable( fd ); GifDrawable gifFromPath = new GifDrawable( "/path/anim.gif" ); File gifFile = new File(getFilesDir(),"anim.gif"); GifDrawable gifFromFile = new GifDrawable(gifFile); AssetFileDescriptor afd = getAssets().openFd( "anim.gif" ); GifDrawable gifFromAfd = new GifDrawable( afd ); InputStream sourceIs = ...; BufferedInputStream bis = new BufferedInputStream( sourceIs, GIF_LENGTH ); GifDrawable gifFromStream = new GifDrawable( bis ); ByteBuffer rawGifBytes = ...; GifDrawable gifFromBytes = new GifDrawable( rawGifBytes ); ``` -------------------------------- ### GifDrawable Initialization Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Methods to construct a GifDrawable from various data sources including assets, resources, files, and streams. ```APIDOC ## GifDrawable Constructor Methods ### Description Constructs a new GifDrawable instance from a specified input source. All sources must support rewinding. ### Parameters - **source** (Object) - Required - Can be AssetManager, Resources, Uri, byte[], FileDescriptor, String (path), File, AssetFileDescriptor, InputStream, or ByteBuffer. ### Usage Example ```java // From Assets GifDrawable gifFromAssets = new GifDrawable(getAssets(), "anim.gif"); // From File File gifFile = new File(getFilesDir(), "anim.gif"); GifDrawable gifFromFile = new GifDrawable(gifFile); ``` ``` -------------------------------- ### Configure CMake Build for Android GIF Library Source: https://github.com/koral--/android-gif-drawable/blob/dev/android-gif-drawable/src/main/c/CMakeLists.txt This CMake script defines the build process for the native shared library. It enables assembly support, dynamically discovers C source files, conditionally includes architecture-specific assembly files, and links the library with essential Android graphics and logging dependencies. ```cmake cmake_minimum_required(VERSION 3.4.1) set(CMAKE_VERBOSE_MAKEFILE on) set(can_use_assembler TRUE) enable_language(ASM) set(SOURCES) file(GLOB_RECURSE SOURCES "*.c") if((${ANDROID_ABI} STREQUAL "armeabi") OR (${ANDROID_ABI} STREQUAL "armeabi-v7a")) list(APPEND SOURCES memset.arm.S) endif() add_library(pl_droidsonroids_gif SHARED ${SOURCES}) set(LIBS jnigraphics android GLESv2 log) target_link_libraries(pl_droidsonroids_gif ${LIBS}) target_link_options(pl_droidsonroids_gif PRIVATE "-Wl,-z,max-page-size=16384") ``` -------------------------------- ### Proguard Configuration for GifDrawable Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Legacy Proguard configuration rules for the GifIOException and GifInfoHandle classes to ensure proper library functionality during code shrinking. ```proguard -keep public class pl.droidsonroids.gif.GifIOException{(int);} -keep class pl.droidsonroids.gif.GifInfoHandle{(long,int,int,int);} ``` -------------------------------- ### GifImageView - XML and Programmatic Usage Source: https://context7.com/koral--/android-gif-drawable/llms.txt Details on using GifImageView as a replacement for ImageView to handle GIF animations, including XML attributes and programmatic control. ```APIDOC ## GifImageView - XML and Programmatic Usage GifImageView is a drop-in replacement for ImageView that automatically handles GIF animations. It recognizes GIF files set via `android:src` or `android:background`. ### XML Usage ```xml ``` ### Programmatic Creation ```java // Programmatic creation GifImageView gifImageView = new GifImageView(context); // Set GIF from resource (automatically recognized) gifImageView.setImageResource(R.drawable.animation); // Set GIF from Uri gifImageView.setImageURI(Uri.parse("file:///sdcard/animation.gif")); // Set background GIF gifImageView.setBackgroundResource(R.drawable.background_animation); // Access the underlying GifDrawable for control Drawable drawable = gifImageView.getDrawable(); if (drawable instanceof GifDrawable) { GifDrawable gifDrawable = (GifDrawable) drawable; gifDrawable.stop(); gifDrawable.setSpeed(1.5f); } // Preserve animation state across configuration changes gifImageView.setFreezesAnimation(true); // Using with MediaController for playback controls final GifDrawable gifDrawable = (GifDrawable) gifImageView.getDrawable(); MediaController mediaController = new MediaController(this); mediaController.setMediaPlayer(gifDrawable); mediaController.setAnchorView(gifImageView); gifImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaController.show(); } }); ``` ``` -------------------------------- ### Using GifTextView for Compound Drawables in Android XML Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md This XML snippet shows how to utilize GifTextView in an Android layout. It allows for animated GIFs to be used as compound drawables (e.g., `drawableTop`, `drawableStart`) or as the background of a TextView. ```xml ``` -------------------------------- ### GifTextureView - Hardware Accelerated Rendering Source: https://context7.com/koral--/android-gif-drawable/llms.txt GifTextureView uses TextureView for hardware-accelerated GIF rendering, offering better performance for complex animations and supporting various scale types similar to ImageView. ```APIDOC ## GifTextureView - Hardware Accelerated Rendering GifTextureView uses TextureView for hardware-accelerated GIF rendering. It's ideal for performance-critical scenarios and supports scale types like ImageView. ### XML Usage ```xml ``` ### Programmatic Usage ```java // Programmatic usage GifTextureView gifTextureView = new GifTextureView(context); // Set input source InputSource source = new InputSource.ResourcesSource(getResources(), R.drawable.animation); gifTextureView.setInputSource(source); // Set from asset InputSource assetSource = new InputSource.AssetSource(getAssets(), "animation.gif"); gifTextureView.setInputSource(assetSource); // Set from file InputSource fileSource = new InputSource.FileSource("/sdcard/animation.gif"); gifTextureView.setInputSource(fileSource); // Set with placeholder drawer gifTextureView.setInputSource(source, new GifTextureView.PlaceholderDrawListener() { @Override public void onDrawPlaceholder(Canvas canvas) { canvas.drawColor(Color.GRAY); // Draw loading indicator } }); // Control animation speed gifTextureView.setSpeed(2.0f); // Set scale type gifTextureView.setScaleType(ImageView.ScaleType.FIT_CENTER); ImageView.ScaleType currentScaleType = gifTextureView.getScaleType(); // Custom matrix transform (only works with ScaleType.MATRIX) gifTextureView.setScaleType(ImageView.ScaleType.MATRIX); Matrix matrix = new Matrix(); matrix.postRotate(45f); gifTextureView.setTransform(matrix); // Mark as opaque for faster rendering (changes restart animation) gifTextureView.setOpaque(true); // Preserve animation state gifTextureView.setFreezesAnimation(true); // Check for errors IOException error = gifTextureView.getIOException(); if (error != null) { Log.e("GIF", "Failed to load: " + error.getMessage()); } // Remove source (clears display) gifTextureView.setInputSource(null); ``` ``` -------------------------------- ### Retrieve GIF Metadata with GifAnimationMetaData Source: https://context7.com/koral--/android-gif-drawable/llms.txt Demonstrates how to extract GIF properties like dimensions, frame count, and memory requirements without loading full pixel data. This is essential for optimizing memory usage before initializing a GifDrawable. ```java GifAnimationMetaData metadata = new GifAnimationMetaData(getResources(), R.drawable.animation); int width = metadata.getWidth(); int height = metadata.getHeight(); long pixelsByteCount = metadata.getAllocationByteCount(); if (pixelsByteCount > MAX_MEMORY_THRESHOLD) { GifDrawable gif = new GifDrawableBuilder().from(getResources(), R.drawable.animation).sampleSize(2).build(); } else { GifDrawable gif = new GifDrawable(getResources(), R.drawable.animation); } ``` -------------------------------- ### Control GIF animation with MediaController Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Shows how to integrate a GifDrawable with an Android MediaController to provide standard playback controls like play, pause, and seek for GIF animations. ```java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GifImageButton gib = new GifImageButton(this); setContentView(gib); gib.setImageResource(R.drawable.sample); final MediaController mc = new MediaController(this); mc.setMediaPlayer((GifDrawable) gib.getDrawable()); mc.setAnchorView(gib); gib.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mc.show(); } }); } ``` -------------------------------- ### GifDecoder - Lightweight Frame Access Source: https://context7.com/koral--/android-gif-drawable/llms.txt Provides low-level access to GIF frames without the overhead of Drawable wrappers, useful for custom rendering or frame extraction. ```APIDOC ## GifDecoder - Lightweight Frame Access GifDecoder provides low-level access to GIF frames without the overhead of Drawable wrappers. Useful for custom rendering or frame extraction. ### Description This section explains how to use `GifDecoder` to access individual frames of a GIF file. It covers creating a decoder, retrieving GIF metadata, rendering frames into a `Bitmap`, and cleaning up resources. ### Usage 1. Create an `InputSource` for your GIF file. 2. Instantiate `GifDecoder` with the `InputSource`, optionally providing `GifOptions`. 3. Use methods like `getWidth()`, `getHeight()`, `getNumberOfFrames()`, `getDuration()`, etc., to get GIF information. 4. Create a `Bitmap` buffer with the correct configuration (`ARGB_8888`) and size. 5. Use `seekToFrame(frameIndex, buffer)` or `seekToTime(timeMillis, buffer)` to render a specific frame into the buffer. 6. You can extract all frames by iterating through `getNumberOfFrames()` and rendering each one into a separate `Bitmap`. 7. Remember to call `recycle()` on the `GifDecoder` when you are finished to release resources. ### Code Example ```java // Create decoder from input source InputSource source = new InputSource.FileSource("/sdcard/animation.gif"); GifDecoder decoder = new GifDecoder(source); // Create decoder with options GifOptions options = new GifOptions(); options.setInSampleSize(2); GifDecoder sampledDecoder = new GifDecoder(source, options); // Get GIF information int width = decoder.getWidth(); int height = decoder.getHeight(); int frameCount = decoder.getNumberOfFrames(); int duration = decoder.getDuration(); int loopCount = decoder.getLoopCount(); boolean isAnimated = decoder.isAnimated(); String comment = decoder.getComment(); long sourceLength = decoder.getSourceLength(); long allocByteCount = decoder.getAllocationByteCount(); // Create buffer bitmap (must be ARGB_8888, size >= GIF size) Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // Seek to specific frame and render into buffer decoder.seekToFrame(0, buffer); // Now buffer contains frame 0 // Seek to specific time position decoder.seekToTime(1500, buffer); // 1.5 seconds // Get frame duration int frameDuration = decoder.getFrameDuration(0); // Extract all frames List frames = new ArrayList<>(); for (int i = 0; i < frameCount; i++) { Bitmap frame = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); decoder.seekToFrame(i, frame); frames.add(frame); } // Clean up decoder.recycle(); ``` ``` -------------------------------- ### Maven Dependency for Android GIF Drawable Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md This XML snippet provides the Maven dependency configuration required to include the android-gif-drawable library in your project. Remember to replace 'insert latest version here' with the actual latest version. ```xml pl.droidsonroids.gif android-gif-drawable insert latest version here aar ``` -------------------------------- ### Metadata Retrieval Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Methods to extract information about the GIF file structure and memory usage. ```APIDOC ## Metadata API ### Description Methods to retrieve details about the GIF, such as frame counts, loop counts, and memory allocation. ### Methods - **getLoopCount()**: Returns loop count from NETSCAPE 2.0 extension. - **getNumberOfFrames()**: Returns total frame count. - **getAllocationByteCount()**: Returns memory size in bytes used by pixels. - **getComment()**: Returns GIF comment text. ``` -------------------------------- ### Animation Control Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Methods to manage the playback state and speed of the GIF animation. ```APIDOC ## Animation Control API ### Description Methods provided by GifDrawable to control playback, implement Animatable and MediaPlayerControl interfaces. ### Methods - **start()**: Starts the animation. - **stop()**: Stops the animation. - **setSpeed(float factor)**: Sets playback speed (e.g., 2.0f for double speed). - **seekTo(int position)**: Seeks to a specific millisecond position. - **isRunning()**: Returns boolean status of animation. ``` -------------------------------- ### Using GifImageView in Android XML Layout Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md This XML snippet demonstrates how to use the GifImageView in an Android layout file to display an animated GIF. The library automatically recognizes GIF files assigned to `android:src` or `android:background` and animates them. ```xml ``` -------------------------------- ### Access GIF frames and metadata with GifDecoder Source: https://context7.com/koral--/android-gif-drawable/llms.txt GifDecoder provides low-level access to GIF data, allowing developers to query metadata, seek to specific frames or timestamps, and render frames into custom Bitmap buffers. This is ideal for scenarios requiring frame extraction or custom rendering logic outside of standard Drawable components. ```java InputSource source = new InputSource.FileSource("/sdcard/animation.gif"); GifDecoder decoder = new GifDecoder(source); int width = decoder.getWidth(); int height = decoder.getHeight(); Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); decoder.seekToFrame(0, buffer); decoder.seekToTime(1500, buffer); List frames = new ArrayList<>(); for (int i = 0; i < decoder.getNumberOfFrames(); i++) { Bitmap frame = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); decoder.seekToFrame(i, frame); frames.add(frame); } decoder.recycle(); ``` -------------------------------- ### GifDrawable - Metadata and Memory Management Source: https://context7.com/koral--/android-gif-drawable/llms.txt Retrieve GIF metadata including dimensions, frame count, duration, and memory usage. Handles GIF errors and provides methods for recycling the drawable. ```java GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.animation); // Get dimensions int width = gifDrawable.getIntrinsicWidth(); int height = gifDrawable.getIntrinsicHeight(); // Get frame information int numberOfFrames = gifDrawable.getNumberOfFrames(); int duration = gifDrawable.getDuration(); // duration of one loop in ms int frameDuration = gifDrawable.getFrameDuration(0); // duration of frame 0 // Get GIF comment (if any) String comment = gifDrawable.getComment(); // Get current frame as a copy Bitmap currentFrame = gifDrawable.getCurrentFrame(); // Get pixel data int[] pixels = new int[width * height]; gifDrawable.getPixels(pixels); int pixel = gifDrawable.getPixel(x, y); // Memory information int frameByteCount = gifDrawable.getFrameByteCount(); long allocationByteCount = gifDrawable.getAllocationByteCount(); long metadataByteCount = gifDrawable.getMetadataAllocationByteCount(); long sourceByteCount = gifDrawable.getInputSourceByteCount(); // Error handling GifError error = gifDrawable.getError(); if (error != GifError.NO_ERROR) { Log.e("GIF", "Error: " + error.name()); } // Recycle when done (also called automatically in finalizer) gifDrawable.recycle(); boolean isRecycled = gifDrawable.isRecycled(); // Debug info Log.d("GIF", gifDrawable.toString()); // Output: "GIF: size: 480x320, frames: 24, error: 0" ``` -------------------------------- ### Associate GifDrawable with multiple Views Source: https://github.com/koral--/android-gif-drawable/blob/dev/README.md Demonstrates how to use MultiCallback to allow a single GifDrawable instance to animate across multiple ImageView components. This is necessary because a standard drawable callback only supports one view at a time. ```java MultiCallback multiCallback = new MultiCallback(); imageView.setImageDrawable(gifDrawable); multiCallback.addView(imageView); anotherImageView.setImageDrawable(gifDrawable); multiCallback.addView(anotherImageView); gifDrawable.setCallback(multiCallback); ``` -------------------------------- ### Synchronize GifDrawable across multiple Views with MultiCallback Source: https://context7.com/koral--/android-gif-drawable/llms.txt MultiCallback enables a single GifDrawable instance to be rendered and animated across multiple ImageView or TextView components. It requires manual management of view registration and callback assignment to ensure proper invalidation. ```java GifDrawable sharedGifDrawable = new GifDrawable(getResources(), R.drawable.animation); MultiCallback multiCallback = new MultiCallback(); ImageView imageView1 = findViewById(R.id.image_view_1); imageView1.setImageDrawable(sharedGifDrawable); multiCallback.addView(imageView1); ImageView imageView2 = findViewById(R.id.image_view_2); imageView2.setImageDrawable(sharedGifDrawable); multiCallback.addView(imageView2); sharedGifDrawable.setCallback(multiCallback); MultiCallback spanCallback = new MultiCallback(true); TextView textView = findViewById(R.id.text_view); SpannableString spannable = new SpannableString("Text with GIF "); ImageSpan imageSpan = new ImageSpan(sharedGifDrawable); spannable.setSpan(imageSpan, spannable.length() - 1, spannable.length(), 0); textView.setText(spannable); spanCallback.addView(textView); sharedGifDrawable.setCallback(spanCallback); ``` -------------------------------- ### GifDrawable - Visual Effects Source: https://context7.com/koral--/android-gif-drawable/llms.txt Apply various visual effects to GifDrawable, including setting corner radius, alpha transparency, color filters, tinting, and custom transforms. Also allows enabling/disabling bitmap filtering and accessing the paint object for advanced customization. ```java GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.animation); // Set corner radius for rounded corners gifDrawable.setCornerRadius(20f); float radius = gifDrawable.getCornerRadius(); // Set alpha (0-255) gifDrawable.setAlpha(128); int alpha = gifDrawable.getAlpha(); // Apply color filter ColorFilter filter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY); gifDrawable.setColorFilter(filter); ColorFilter currentFilter = gifDrawable.getColorFilter(); // Apply tint gifDrawable.setTintList(ColorStateList.valueOf(Color.BLUE)); gifDrawable.setTintMode(PorterDuff.Mode.SRC_ATOP); // Enable/disable bitmap filtering gifDrawable.setFilterBitmap(true); // Custom transform for advanced drawing Transform customTransform = new Transform() { @Override public void onBoundsChange(Rect bounds) { // Handle bounds change } @Override public void onDraw(Canvas canvas, Paint paint, Bitmap buffer) { // Custom drawing logic canvas.drawBitmap(buffer, 0, 0, paint); } }; gifDrawable.setTransform(customTransform); // Get paint for advanced customization Paint paint = gifDrawable.getPaint(); paint.setAntiAlias(true); ``` -------------------------------- ### GifDrawable - Animation Listener Source: https://context7.com/koral--/android-gif-drawable/llms.txt Register and remove listeners to be notified when animation loops complete. Allows for actions to be triggered after animation finishes or to count completed loops. Supports setting a specific loop count. ```java GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.animation); // Add animation listener AnimationListener listener = new AnimationListener() { @Override public void onAnimationCompleted(int loopNumber) { Log.d("GIF", "Loop " + loopNumber + " completed"); // Stop after 3 loops if (loopNumber >= 2) { gifDrawable.stop(); } } }; gifDrawable.addAnimationListener(listener); // Remove listener when no longer needed gifDrawable.removeAnimationListener(listener); // Set a specific loop count gifDrawable.setLoopCount(5); // Will complete after 5 loops gifDrawable.start(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.