Issue
Flutter: How to get the pixel color when tapping somewhere on an image?
Solution
You can get the touch position by using a GestureDetector
, and then the pixel color by using the ImagePixels
widget from the image_pixels package:
ImagePixels(
imageProvider: ...,
builder: (BuildContext context, ImgDetails img) {
var color = img.pixelColorAt(x, y);
This is a working example:
import 'package:image_pixels/image_pixels.dart';
...
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, this.title}) : super(key: key);
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final AssetImage flutter = const AssetImage("lib/images/FlutterLogo.jpg");
Offset localPosition = const Offset(-1, -1);
Color color = const Color(0x00000000);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand(
child: Column(
children: [
const Expanded(
flex: 1,
child: Center(
child: Text('Tap the image to see the pixel color:'),
),
),
Expanded(
flex: 4,
child: Padding(
padding: const EdgeInsets.all(40.0),
child: Center(
child: Container(
color: Colors.grey,
child: Listener(
onPointerMove: (PointerMoveEvent details) {
setState(() {
localPosition = details.localPosition;
});
},
onPointerDown: (PointerDownEvent details) {
setState(() {
localPosition = details.localPosition;
});
},
child: ImagePixels(
imageProvider: flutter,
builder: (BuildContext context, ImgDetails img) {
var color = img.pixelColorAt!(
localPosition.dx.toInt(),
localPosition.dy.toInt(),
);
WidgetsBinding.instance!.addPostFrameCallback((_) {
if (mounted)
setState(() {
if (color != this.color) this.color = color;
});
});
return SizedBox(
width: 150,
height: 213,
child: Image(image: flutter),
);
})))))),
Expanded(
flex: 2,
child: Column(
children: [
Container(width: 75, height: 55, color: color),
Container(height: 20),
Text(localPosition.toString()),
],
),
),
],
),
),
);
}
}
Get the code from GitHub.
Note: I am the author of the package.
Answered By - MarcG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.