foreword
There is such a scene, in an app that displays a lot of text, the background image can be customized, of course it can also be dynamic, but this homepage can be shared, that is, I need to write text on a dynamic background and save it Create a new picture and share it.
accomplish
Preparation
Need to import an image library, the current version is 4.0.17
implement logic
It is very simple to add text to a static image. You only need to decode the image file into memory, convert it into any Image instance, and then perform further operations on this instance to draw text. What about animations? A moving picture is actually a lot of pictures stacked together and displayed according to the frame rate. Then we only need to get the pictures of each frame and draw text on the pictures of each frame?
Implementation
Let's create a new dart file casually, let's try it first
import 'package:image/image.dart';
void main(){
generateGif("hello");
}
void generateGif(String text) async{
final sparkWebp = await decodeWebPFile("webp_video/sparkler.webp");
Image image = Image(width: sparkWebp!.width, height: sparkWebp.height);
for(Image frame in sparkWebp.frames){
final addStringWebp = drawString(frame, text, font: arial24);
image.addFrame(addStringWebp);
}
bool res = await encodeGifFile("test.gif", image);
print(res);
// final addStringWebp = drawString(sparkWebp!, "hello", font: arial24);
//encodePngFile("callTest.png", addStringWebp);
}
It worked! The left side is the original image webp, the right side is the exported gif, and the file is generated in the project root directory
Note: The picture comes from the Internet, if there is any infringement, please contact to delete
implementation details
Here we use the drawString() method to write text, and we can see from the incoming parameters that a BitmapFont must be passed in, and a bitmap font (fnt) must be passed in. Since only bitmap fonts are supported, only English and special fonts can be drawn at present. character
The x and y here are the position of the specified text. If not specified, it will be centered and aligned by default. You can also specify colors and other effects. I won’t list them one by one. You can explore by yourself!
Image drawString(Image image, String string,
{required BitmapFont font,
int? x,
int? y,
Color? color,
bool rightJustify = false,
bool wrap = false,
Image? mask,
Channel maskChannel = Channel.luminance})