我试图在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>
这个想法是&#34; pan / zoom&#34;一个图像,以便它不依赖于容器的尺寸(这就是为什么我把一个样式用百分比)。
我尝试通过CustomPainter实现这一点,但我无法弄清楚要传递给paintImage()方法的绘制Rectangle。看起来画布左上角与要绘制的容器的左上角不对应。
以下是部分代码:
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;
}
}
我现在已经挣扎了几个小时......
有人可以帮助我吗?
非常感谢
答案 0 :(得分: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
绘制图像我希望这会有所帮助。
享受!