flutter自绘组件,实现图片展示在屏幕正中间,图片宽高自适应,图片可拖动,放大缩小,写出示例代码。
时间: 2024-06-13 15:08:32 浏览: 159
flutter插件
以下是一个Flutter自绘组件的示例代码,可以实现图片展示在屏幕正中间,图片宽高自适应,图片可拖动,放大缩小的功能:
```dart
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'dart:math' as math;
class ImageEditor extends StatefulWidget {
final ImageProvider imageProvider;
ImageEditor({Key key, this.imageProvider}) : super(key: key);
@override
_ImageEditorState createState() => _ImageEditorState();
}
class _ImageEditorState extends State<ImageEditor> {
double _scale = 1.0;
double _previousScale = 1.0;
Offset _offset = Offset.zero;
Offset _previousOffset = Offset.zero;
Size _imageSize;
@override
Widget build(BuildContext context) {
return GestureDetector(
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
onScaleEnd: _handleScaleEnd,
child: CustomPaint(
painter: _ImagePainter(
imageProvider: widget.imageProvider,
scale: _scale,
offset: _offset,
imageSize: _imageSize,
),
child: SizedBox.expand(),
),
);
}
void _handleScaleStart(ScaleStartDetails details) {
_previousScale = _scale;
_previousOffset = _offset;
}
void _handleScaleUpdate(ScaleUpdateDetails details) {
setState(() {
_scale = _previousScale * details.scale;
_offset = _previousOffset +
(details.focalPoint - details.localFocalPoint) / _scale;
});
}
void _handleScaleEnd(ScaleEndDetails details) {
_previousScale = 1.0;
_previousOffset = _offset;
}
@override
void initState() {
super.initState();
Image image = Image(image: widget.imageProvider);
image.image.resolve(ImageConfiguration()).addListener(
ImageStreamListener((info, _) {
setState(() {
_imageSize = Size(
info.image.width.toDouble(),
info.image.height.toDouble(),
);
});
}),
);
}
}
class _ImagePainter extends CustomPainter {
final ImageProvider imageProvider;
final double scale;
final Offset offset;
final Size imageSize;
_ImagePainter({
this.imageProvider,
this.scale,
this.offset,
this.imageSize,
});
@override
void paint(Canvas canvas, Size size) async {
Paint paint = Paint();
paint.isAntiAlias = true;
paint.filterQuality = FilterQuality.high;
Rect rect = Offset.zero & size;
canvas.clipRect(rect);
if (imageSize != null) {
double width = imageSize.width * scale;
double height = imageSize.height * scale;
double x = offset.dx + (size.width - width) / 2;
double y = offset.dy + (size.height - height) / 2;
Rect imageRect = Rect.fromLTWH(x, y, width, height);
ui.Image image = await imageProvider.resolve(
ImageConfiguration(
size: Size(imageRect.width, imageRect.height),
),
);
canvas.drawImage(image, imageRect.topLeft, paint);
}
}
@override
bool shouldRepaint(_ImagePainter oldDelegate) {
return oldDelegate.scale != scale ||
oldDelegate.offset != offset ||
oldDelegate.imageSize != imageSize;
}
}
```
阅读全文