はじめに
OpenLayersを利用して、ポリゴン図形にハッチパターンで塗りつぶす際のメモ
OpenLayersのデモでは例がなく実装が難しそうだったので、ol-extのol.style.FillPatternクラスを利用した。
実装例
ハッチパターンは、自作するのが大変なので、C#のHatchStyleを利用し、画像を生成し、
その画像を使って、ol.style.FillPatternクラスでレンダリングを行う。
ImageController.cs
C#のHatchStyleの画像を生成する、ASP.NetのApiControllerを作成します。
引数に、HatchStyleや色、サイズなどを指定し、任意のハッチパターン画像を返却します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class ImageController : ApiController { public HttpResponseMessage GetHatchStyle(string style, int width, int height ,string color = "0x000000") { var response = new HttpResponseMessage(); var imgconv = new ImageConverter(); byte[] bytes = null; using (var image = new Bitmap(width, height)) { using (var graphics = Graphics.FromImage(image)) { image.MakeTransparent(); if (!string.IsNullOrEmpty(style)) { var hatchStyle = HatchStyle.Horizontal; Enum.TryParse(style, out hatchStyle); var frColor = ColorTranslator.FromHtml(color.Replace("0x","#")); var brush = new HatchBrush(hatchStyle, frColor, Color.Transparent); var rect = new Rectangle(0, 0, width, height); graphics.FillRectangle(brush, rect); } bytes = (byte[])imgconv.ConvertTo(image, typeof(byte[])); } } response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(bytes); response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return response; } } } |
HatchStyle.js
作成したレイヤのスタイルにol.style.FillPatternクラスを利用します。
ただし、ol.style.FillPatternクラスで定義されたパターンは使用せず、自作のImageControllerクラスを呼び出します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
var map = new ol.Map({ target: 'MapPanel', view: new ol.View({ center: [14897735, 4070125], zoom: 15, minZoom: 10, maxZoom: 18 }) }); var vectorSource = new ol.source.Vector( { projection: 'EPSG:3857', format: new ol.format.GeoJSON(), strategy: ol.loadingstrategy.all, loader: function (extent, resolution, projection) { var fjson = LoadJson("../../Api/Layer/GetFeatures?layername=" + ""); var features = new ol.format.GeoJSON().readFeatures(fjson); this.addFeatures(features); } }); var openlayer = new ol.layer.Vector({ name: "", source: vectorSource, visible: layerjson.Visible, opacity: layerjson.Opacity, style: function (feature, resolution) { var style = new ol.style.Style({ fill: new ol.style.FillPattern({ image: new ol.style.Icon({ src : "../../Api/Image/GetHatchStyle?style=DiagonalCross&width=16&height=16&color=0x000080" }, scale: 1.0 }) }); return style; } }); map.addLayer(openlayer); |
画面イメージ
設定画面
設定画面のイメージも自作のImageControllerクラスを利用しています。
地図画面
ポリゴン図形がハッチパターンで塗りつぶされています。