You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:如何计算图片中心点坐标以获取该位置像素颜色

解决Flutter获取图片中心点像素颜色的坐标计算问题

要获取图片中心点的像素坐标,直接取图片宽高的整数半值即可——因为图片的像素坐标从左上角(0,0)开始计数,中心点的x坐标为宽度的一半,y坐标为高度的一半,用整数除法~/来避免小数问题。

修改你的代码如下:

Widget hanldeimagepixelColor(BuildContext context) {
  Image img = Image.file(File(imagepathfile!.path));
  return ImagePixels(
      imageProvider: img.image,
      builder: (context, img) {
        int imgWidth = img.width!;
        int imgHeight = img.height!;
        // 计算中心点坐标
        int xRelative = imgWidth ~/ 2;
        int yRelative = imgHeight ~/ 2;
        Color color = img.pixelColorAt!(xRelative, yRelative);
        return Container(
          height: 30,
          width: 30,
          color: color,
        );
      });
}

关键点说明:

  • img.width!和img.height!:在ImagePixels的builder回调中,图片已完成加载,宽高不会为null,可直接用!断言。
  • ~/:Flutter中的整数除法运算符,会自动向下取整,刚好匹配像素坐标的整数要求。比如宽度为101时,101~/2=50,对应中心点的像素位置。

内容的提问来源于stack exchange,提问作者user15141168

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:55:22