Rya*_*ang 4 dart flutter flutter-dependencies
一个非常简单的问题:如何为 Flutter 相机插件实现点击对焦功能?
\n我\xe2\x80\x99已经搜索了整个万维网的解决方案,但我什么也没找到。
\n有人有想法吗?
\nnic*_*er 10
您必须使用相机控制器方法手动设置焦点:
controller.setFocusPoint(offset)
Run Code Online (Sandbox Code Playgroud)
请参阅此处的官方 Api 文档,了解方法和相机功能。
该方法需要一个焦点。x,y 点必须 > 0 且 < 1,其中 0 是相机的左上角点,1 是右下角点。
然后您必须检索相机尺寸并创建比例。
这是完整的示例代码,您可以复制并运行
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
late List<CameraDescription> cameras;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(const MaterialApp(home: CameraApp()));
}
class CameraApp extends StatefulWidget {
const CameraApp({Key? key}) : super(key: key);
@override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
late CameraController controller;
bool showFocusCircle = false;
double x = 0;
double y = 0;
@override
void initState() {
super.initState();
controller = CameraController(cameras[0], ResolutionPreset.max);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
return GestureDetector(
onTapUp: (details) {
_onTap(details);
},
child: Stack(
children: [
Center(
child: CameraPreview(controller)
),
if(showFocusCircle) Positioned(
top: y-20,
left: x-20,
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white,width: 1.5)
),
))
],
)
);
}
Future<void> _onTap(TapUpDetails details) async {
if(controller.value.isInitialized) {
showFocusCircle = true;
x = details.localPosition.dx;
y = details.localPosition.dy;
double fullWidth = MediaQuery.of(context).size.width;
double cameraHeight = fullWidth * controller.value.aspectRatio;
double xp = x / fullWidth;
double yp = y / cameraHeight;
Offset point = Offset(xp,yp);
print("point : $point");
// Manually focus
await controller.setFocusPoint(point);
// Manually set light exposure
//controller.setExposurePoint(point);
setState(() {
Future.delayed(const Duration(seconds: 2)).whenComplete(() {
setState(() {
showFocusCircle = false;
});
});
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意添加 x,y 点值的边界,以避免点击超出相机预览时崩溃:
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
Run Code Online (Sandbox Code Playgroud)
此外,据我所知, iOS前置摄像头无法对焦点,因此仅允许在后置摄像头镜头上点击对焦。
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |