【问题标题】:Flutter: CustomPainter difficulties with offset determinationFlutter:CustomPainter 难以确定偏移量
【发布时间】:2018-03-26 15:00:03
【问题描述】:

我试图在 Flutter 中实现以下目标,但我失败了

<style>
   #square {
      display: block;
      width:  300px;
      height: 300px;
      overflow: hidden;
   }

   #square img {
     position: absolute;
   }
</style>
<body>
   <div id="square">
     <img src="whatever.jpg" style="left:-5%;top:-10%;width:130%" />
   </div>
</body>

这个想法是“平移/缩放”图像,使其不依赖于容器的尺寸(这就是我放置百分比样式的原因)。

我试图通过 CustomPainter 来实现这一点,但我无法确定要传递给 paintImage() 方法的绘制矩形。画布的左上角似乎与要绘制的容器的左上角不对应。

这里是部分代码:

class _ImagePainter extends CustomPainter {
  const _ImagePainter({this.image, this.leftPercent, this.topPercent, this.widthPercent});

  final ui.Image image;
  final double leftPercent;
  final double topPercent;
  final double widthPercent;

  //
  //  How to compute the theOffset ???
  //
  Offset offset;


  @override
  void paint(Canvas canvas, Size size) {
    paintImage(canvas: canvas, rect: offset & (size * widthPercent), image: image, fit:BoxFit.contain, alignment: Alignment.topLeft);
  }

  @override
  bool shouldRepaint(_ZoomableImagePainter old) {
    return old.image != image || old.leftPercent != leftPercent || old.topPercent != topPercent  || old.widthPercent != widthPercent;
  }
}

我现在已经挣扎了好几个小时......

谁能帮帮我?

非常感谢

【问题讨论】:

    标签: flutter


    【解决方案1】:

    好吧,我终于知道了……

    代码如下:

    class _ImagePainter extends CustomPainter {
      const _ImagePainter({this.image, this.leftPercent, this.topPercent, this.widthPercent});
    
      final ui.Image image;
      final double leftPercent;
      final double topPercent;
      final double widthPercent;
    
      @override
      void paint(Canvas canvas, Size size) {
        //
        //  This is how to compute both offset and paintRectangle
        //
        double imageWidhHeightRatio = image.width.toDouble() / image.height.toDouble();
        Offset offset = new Offset(leftPercent * size.width, topPercent * size.height);
        Rect imagePaintRect = new Rect.fromLTRB(offset.dx, offset.dy, offset.dx + size.width * widthPercent, offset.dy + size.height * widthPercent / imageWidthHeightRatio);
    
        paintImage(canvas: canvas, rect: imagePaintRect, image: image, fit:BoxFit.fill, alignment: Alignment.topLeft);
      }
    
      @override
      bool shouldRepaint(_ZoomableImagePainter old) {
        return old.image != image || old.leftPercent != leftPercent || old.topPercent != topPercent  || old.widthPercent != widthPercent;
      }
    }
    

    诀窍是: 1. 我们需要考虑将图像绘制到的矩形,作为其尺寸重新缩放到目标区域的区域。 2. 绘制图像,使用 BoxFit.fill

    我希望这会有所帮助。

    享受吧!

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2015-11-28
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2017-12-26
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多