flutter开发实战-Camera自定义相机拍照功能实现
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
class CameraApp extends StatefulWidget {
@override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
CameraController _controller;
Future<void> _initializeControllerFuture;
@override
void initState() {
super.initState();
_controller = CameraController(cameras[0], ResolutionPreset.medium);
_initializeControllerFuture = _controller.initialize();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(_controller);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
try {
await _initializeControllerFuture;
final path = join(
(await getApplicationDocumentsDirectory()).path,
'${DateTime.now()}.png',
);
await _controller.takePicture(path);
} catch (e) {
print(e);
}
},
child: Icon(Icons.camera_alt),
),
);
}
}
这段代码实现了一个简单的相机预览界面,并在底部浮动按钮点击时触发拍照功能。它展示了如何使用Flutter的camera
插件来初始化相机控制器,预览相机画面,并在用户点击拍照按钮时保存一张照片到设备文件系统。
评论已关闭