首页 > 解决方案 > 是否可以在 Flutter 中的图像文件上绘制文本?

问题描述

这是我一直在使用的代码,这个问题有时是在 iOS 中,文本会出现在图像之外并剪切。我希望文本在右下角的图像中正确换行。

PS 这不是 UI 问题...我想在图像文件上绘制文本并将其用于进一步的目的,而不仅仅是在 UI 上。

Future<File?> drawTextOnImage() async {
        final ImagePicker _picker = ImagePicker();
        // Capture a photo
        final image = await _picker.pickImage(
            source: ImageSource.camera,
            maxHeight: 366,
            maxWidth: 550,
            imageQuality: 50);
        final position = await locationManager.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.high);
        if (image != null) {
          var decodeImg = UIImage.decodeImage(File(image.path).readAsBytesSync());
          final TextToDraw =
              'Lat: ${position.latitude}\nLong:${position.longitude}';
          var stringWidth = 10;
          var stringHeight = 10;
          final chars = TextToDraw.codeUnits;
          for (var c in chars) {
            if (!UIImage.arial_14.characters.containsKey(c)) {
              continue;
            }
            final ch = UIImage.arial_14.characters[c]!;
            stringWidth += ch.xadvance;
            if (ch.height + ch.yoffset > stringHeight) {
              stringHeight = ch.height + ch.yoffset;
            }
          }
    
          if (decodeImg != null) {
            UIImage.drawString(
                decodeImg,
                UIImage.arial_14,
                decodeImg.width - stringWidth,
                decodeImg.height - stringHeight,
                TextToDraw);
    
            var encodeImage = UIImage.encodeJpg(decodeImg, quality: 100);
    
            var finalImage = File(image.path)..writeAsBytesSync(encodeImage);
    
            return finalImage;
          }
        }
    
        helper.ToastFlutter('Problem Fetching Image, Please Try again');
        return null;
      }

标签: flutterdartflutter-layout

解决方案


推荐阅读