I am trying to get the properties of CustomPainter elements when tapped. However, the location generated by onTapUp is not within the path created by CustomPainter Path.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Offset _tapPosition = Offset.zero;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Custom Paint Example'),
),
body: GestureDetector(
onTapDown: (TapDownDetails details) {
// Handle tap here
print('Tap location: ${details.localPosition}');
print('Tap location: ${details.globalPosition}');
final RenderBox renderBox = context.findRenderObject() as RenderBox;
final Offset localOffset = renderBox.localToGlobal(details.globalPosition);
Offset customPaintPosition = renderBox.localToGlobal(Offset.zero);
print(Offset.zero);
if (isTapInsidePath(LinePainter.path_1, details.localPosition)) {
print('Tapped inside path_1 at ${details.localPosition}');
// You can add logic to get the color at the tap position if needed.
}
// _handleClick(details.localPosition);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 10.0,
),
),
child: CustomPaintExample(),
), ),
),
);
}
bool isTapInsidePath(Path path, Offset tapPosition) {
print (path.getBounds());
print (path.computeMetrics());
return path.contains(tapPosition);
}
}
class CustomPaintExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: CustomPaint(
painter: LinePainter(),
size: Size(300, 300),
),
);
}
}
class LinePainter extends CustomPainter {
static final Path path_1 = Path()
..moveTo(167.309,177.39)
..cubicTo(180.907,163.368,200.541,152.36499999999998,213.487,149.762)
..cubicTo(170.764,142.488,175.079,155.056,167.309,177.39)
..close();
// static final Path path_1 = Path();
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = Colors.blue
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
// Define a set of lines to be drawn on the canvas
List<Offset> points = [
Offset(50, 50),
Offset(150, 100),
Offset(100, 200),
Offset(200, 250),
];
// Draw lines on the canvas
for (int i = 0; i < points.length - 1; i++) {
canvas.drawLine(points[i], points[i + 1], paint);
}
Paint paint_1_fill = Paint()..style=PaintingStyle.fill;
paint_1_fill.color = Color(0xff000000).withOpacity(1.0);
canvas.drawPath(path_1,paint_1_fill);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
I have checked that the offset is 0. I have also checked the path.bounds(), which did not seem right. Below is the code. Location when tapped: flutter: 256.3333282470703‘ and 527.0 Bounds from path_1: Rect.fromLTRB(167.3, 142.5, 213.5, 177.4)
I have used global location as well.