ImageSharp icon indicating copy to clipboard operation
ImageSharp copied to clipboard

feat: Add animation loop control to DrawImage with repeatCount parameter

Open Yushu2606 opened this issue 2 months ago • 4 comments

Prerequisites

  • [x] I have written a descriptive pull-request title
  • [x] I have verified that there are no overlapping pull-requests open
  • [x] I have verified that I am following the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules :cop:.
  • [ ] I have provided test coverage for my change (where applicable)

Description

This pull request enhances the DrawImage functionality by adding animation loop control through a new repeatCount parameter. This allows users to control how many times animated images (GIFs, APNGs, WebP animations, etc.) should loop when drawn onto another image. Close #2997

Changes Made

  • Added repeatCount parameter to all DrawImage extension methods in DrawImageExtensions.cs
  • Updated DrawImageProcessor constructors to accept and store the repeatCount parameter
  • Enhanced DrawImageProcessor<TPixelBg, TPixelFg> with animation frame cycling logic:
    • Added currentFrameLoop field to track animation progress
    • Implemented frame selection based on current loop count
    • Added validation to ensure repeatCount >= 0
    • Added loop termination logic (0 = infinite, >0 = specific count)

Key Features

  • Animation Control: repeatCount parameter controls how many times an animated image loops
    • 0 = infinite loop
    • >0 = specific number of loops
  • Frame Cycling: Automatically cycles through animation frames based on loop count
  • Backward Compatibility: All existing DrawImage method signatures are preserved with the new parameter added

Usage Example

// Draw animated GIF with infinite loop
image.DrawImage(animatedGif, opacity: 0.8f, repeatCount: 0);

// Draw animated GIF with 3 loops
image.DrawImage(animatedGif, opacity: 0.8f, repeatCount: 3);

// Draw at specific location with animation control
image.DrawImage(animatedGif, new Point(10, 10), opacity: 0.8f, repeatCount: 2);

Technical Details

  • The implementation tracks the current frame loop using currentFrameLoop field
  • Frame selection uses modulo operation: currentFrameIndex = currentFrameLoop % ForegroundImage.Frames.Count
  • Loop termination is handled by checking if current loop count exceeds the specified repeatCount
  • Validation ensures repeatCount is non-negative using Guard.MustBeGreaterThanOrEqualTo

Images

before after (loop count is 0)
Image Image

Yushu2606 avatar Oct 11 '25 03:10 Yushu2606