【问题标题】:Scaling the icon-image size to an absolute value将图标图像大小缩放为绝对值
【发布时间】:2019-08-14 19:14:06
【问题描述】:

我正在开发一个应用程序,其中一个功能是使用开放图层在地图上显示设备。这些设备可以由用户添加,并且它们都可以使用上传的图像具有自定义图标图像。此图像也可以在运行时根据某些设备属性(例如温度)进行更改。根据我阅读他们的文档的理解,ol.style.Icon 对象上有一些属性,例如 imgSize,它们都是切割的,但没有缩放图像。还有一个称为 scale 的属性,它实际上会缩放图像。但由于图像大小可能会有所不同,因此比例并不总是相同,必须进行计算才能在每个设备上拥有相同的图标大小(40 宽)。

为了根据设备计算正确的图标,我在 layer.Vector 对象上使用了这个样式函数。

function(feature){
  var device = feature.get("device");
  var icon = (device.familyIds.length > 0 ? icons.find(i => i.familyIds.includes(device.familyIds[0])) : undefined);
  return new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 1],
      src: (icon != undefined ? new Function("device", "familyProperty", icon.iconSource)(device, icon.familyProperty) : './img/icons/icon_default.png')
    }),
    text: new ol.style.Text({
      text: device.name,
      offsetY: 15,
      font: "20px Calibri,sans-serif"
    })
  });
}

当某个设备有要显示的图标时,我将代码注入到功能中。此函数返回所需的 img-src。当设备没有图标时,我显示的是默认图标。 所以到目前为止,我设法根据每个设备显示正确的图标,但我仍然在为不同的图像尺寸而苦苦挣扎。我尝试使用 imgSize、大小和比例以各种可以想象的方式配置 ol.style.Icon 对象中的属性,但没有任何效果。 感谢您的帮助。

【问题讨论】:

    标签: javascript jquery openlayers openlayers-5


    【解决方案1】:

    我建议你使用由 src url 索引的样式缓存(在任何情况下都更有效应该可以解决异步问题)

    var styleCache = {};
    
    var styleFunction = function(feature){
      var device = feature.get("device");
      var icon = (device.familyIds.length > 0 ? icons.find(i => i.familyIds.includes(device.familyIds[0])) : undefined);
      var url = (icon != undefined ? new Function("device", "familyProperty", icon.iconSource)(device, icon.familyProperty) : './img/icons/icon_default.png');
      var style = styleCache[url];
      if (!style) {
        style = new ol.style.Style({
          image: new ol.style.Icon({
            anchor: [0.5, 1],
            src: url,
            scale: 0
          }),
          text: new ol.style.Text({
            offsetY: 15,
            font: "20px Calibri,sans-serif"
          })
        });
        var img = new Image();
        img.onload = function() {
          style.getImage().setScale(40/img.width);
          feature.changed();  // force a refresh or just wait until next render?
        }
        img.src = url;
        styleCache[url] = style;
      }
      style.getText().setText(device.name);
      return style;
    }
    

    设备名称文本需要“按需”设置,因为设备可能会共享图像。

    【讨论】:

    • 非常感谢。正是我想要的。到目前为止,他们还没有实现绝对缩放属性,这对我来说仍然有点奇怪。无论如何,谢谢你的帮助。
    【解决方案2】:

    如果太大,缩放图标 -> 图像:new ol.style.Icon(....):

    scale: 0.4,
    

    【讨论】:

    • 这没有帮助。你读过这个问题吗? (不同大小的不同图片)
    • 获取图片大小并计算比例:stackoverflow.com/questions/11442712/…
    • 加载图像以计算比例是异步的,而向量中的样式函数需要立即返回值。您不能简单地加载图像,等待然后返回父函数。这不是 javascript 的工作方式。
    • 这有什么帮助??
    • 在事件触发时样式函数已经完成 - 它由 OpenLayers 调用,开发人员无法控制。
    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2023-01-26
    • 2018-04-10
    • 1970-01-01
    • 2013-10-04
    • 2014-05-23
    相关资源
    最近更新 更多