I am processing images clicked by the camera to add text to them. I need to align the text on the image to either of the 3 positions: Bottom left, bottom center, bottom right. The problem is that the positioning is not consistent as the text can be different in length and size (font size) for each user. Here is how I am trying to calculate the offset (text position). This is far from perfect.
///
Future<Offset> calculateOffsetBasedOnPosition(
TextPosition position, File imageFile, int fontSize, String text) async {
img.Image? image = img.decodeImage(await imageFile.readAsBytes());
if (image != null) {
double margin = 10; // Margin from edges
double estimatedCharWidth =
fontSize * 0.5; // Estimate average character width
double textWidth = estimatedCharWidth * text.length; // Estimate text width
double x = margin; // Default for left alignment
double subtrationFactor = fontSize * 2.5;
double y = image.height - subtrationFactor; // Bottom position with margin
if (position == TextPosition.bottomCenter) {
x = (image.width / 2) - (textWidth / 2); // Center alignment
} else if (position == TextPosition.bottomRight) {
x = image.width - textWidth - margin; // Right alignment
}
// Clamp x value to ensure it's within the image boundaries
x = x.clamp(0.0, image.width - textWidth);
return Offset(x, y);
} else {
throw Exception('Unable to decode image');
}
}
I am using the image and image_editor packages. Is there a package/way where I can have consistent positioning (margins, etc) for the text on the image. Please understand this is different from just displaying text on an image which can be achieved using a stack, etc.