Apply mosaic rule to rasters

View on GitHub

Apply mosaic rule to a mosaic dataset of rasters.

Image of Apply mosaic rule to rasters sample

Use case

An image service can use a mosaic rule to mosaic multiple rasters on-the-fly. A mosaic rule can specify which rasters are selected, and how the selected rasters are z-ordered. It can also specify how overlapping pixels from different rasters at the same location are resolved.

For example, when using the "byAttribute" mosaic method, the values in an attribute field are used to sort the images, and when using the "Center" method, the image closest to the center of the display is positioned as the top image in the mosaic. Additionally, the mosaic operator allows you to define how to resolve the overlapping cells, such as choosing a blending operation.

Specifying mosaic rules is useful for viewing overlapping rasters. For example, using the "By Attribute" mosaic method to sort the rasters based on their acquisition date allows the newest image to be on top. Using "mean" mosaic operation makes the overlapping areas contain the mean cell values from all the overlapping rasters.

How to use the sample

When the rasters are loaded, choose from a list of preset mosaic rules to apply to the rasters.

How it works

  1. Create an ImageServiceRaster using the service's URL.
  2. Create a MosaicRule object and set it to the mosaicRule property of the image service raster.
  3. Create a RasterLayer from the image service raster and add it to the map.
  4. Set the mosaicMethod, mosaicOperation, and other properties of the mosaic rule object accordingly to specify the rule on the raster dataset.

Relevant API

  • ImageServiceRaster
  • MosaicMethod
  • MosaicOperation
  • MosaicRule

About the data

This sample uses a raster image service that shows aerial images of Amberg, Germany.

Additional information

For more information, see Understanding the mosaicking rules for a mosaic dataset from ArcGIS Desktop documentation. To learn more about how to define certain mosaic rules, see Mosaic rule objects from the ArcGIS REST API documentation.

Tags

image service, mosaic method, mosaic rule, raster

Sample Code

ApplyMosaicRuleToRastersView.swift
Use dark colors for code blocksCopy
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Copyright 2024 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import ArcGIS
import SwiftUI

struct ApplyMosaicRuleToRastersView: View {
    /// The tracking status for the loading operation.
    @State private var isLoading = false

    /// The error shown in the error alert.
    @State private var error: Error?

    /// The data model for the sample.
    @StateObject private var model = Model()

    /// Holds the reference to the currently selected rule.
    @State private var ruleSelection: RuleSelection = .objectID

    var body: some View {
        MapViewReader { mapProxy in
            MapView(map: model.map)
                .onDrawStatusChanged { drawStatus in
                    // Updates the the loading state when the map's draw status is completed.
                    withAnimation {
                        if drawStatus == .completed {
                            isLoading = false
                        }
                    }
                }
                .overlay(alignment: .center) {
                    if isLoading {
                        ProgressView("Loading...")
                            .padding()
                            .background(.ultraThickMaterial)
                            .cornerRadius(10)
                            .shadow(radius: 50)
                    }
                }
                .task {
                    guard let rasterLayer = model.map.operationalLayers.first as? RasterLayer else {
                        return
                    }
                    do {
                        // Downloads raster from online service.
                        try await rasterLayer.load()
                        await mapProxy.setViewpoint(
                            Viewpoint(
                                center: model.imageServiceRasterCenter,
                                scale: 25000
                            )
                        )
                    } catch {
                        self.error = error
                    }
                }
                .toolbar {
                    ToolbarItemGroup(placement: .bottomBar) {
                        Picker("Mosaic Rule", selection: $ruleSelection) {
                            ForEach(RuleSelection.allCases, id: \.self) { rule in
                                Text(rule.label)
                            }
                        }
                        .task(id: ruleSelection) {
                            isLoading = true
                            model.imageServiceRaster.mosaicRule = ruleSelection.rule
                            await mapProxy.setViewpoint(
                                Viewpoint(
                                    center: model.imageServiceRasterCenter,
                                    scale: 25000
                                )
                            )
                        }
                        .pickerStyle(.automatic)
                    }
                }
        }
        .errorAlert(presentingError: $error)
    }
}

private enum RuleSelection: CaseIterable, Equatable {
    case objectID, northWest, center, byAttribute, lockRaster

    /// The string to be displayed for each `RuleSelection` option.
    var label: String {
        switch self {
        case .objectID: "Object ID"
        case .northWest: "North West"
        case .center: "Center"
        case .byAttribute: "By Attribute"
        case .lockRaster: "Lock Raster"
        }
    }

    /// For the selected rule type it creates a new `MosaicRule`
    /// and applies the selected and attributes.
    var rule: MosaicRule {
        let mosaicRule = MosaicRule()
        switch self {
        case .objectID:
            // The default mosaic method is objectID which
            // functionally is the same as the none rule in earlier versions.
            mosaicRule.mosaicMethod = .objectID
        case .northWest:
            // Sets the mosaic rule method to northwest method and sets operation
            // to first.
            mosaicRule.mosaicMethod = .northwest
            mosaicRule.mosaicOperation = .first
        case .center:
            // Sets the mosaic method to center and uses blend operation.
            mosaicRule.mosaicMethod = .center
            mosaicRule.mosaicOperation = .blend
        case .byAttribute:
            // Sets the mosaic method to attribute and sorts on "OBJECTID"
            // field of the service.
            mosaicRule.mosaicMethod = .attribute
            mosaicRule.sortField = "OBJECTID"
        case .lockRaster:
            // Sets the mosaic method to lockRaster method and locks 3 image rasters.
            mosaicRule.mosaicMethod = .lockRaster
            mosaicRule.addLockRasterIDs([1, 7, 12])
        }
        return mosaicRule
    }
}

private extension ApplyMosaicRuleToRastersView {
    class Model: ObservableObject {
        /// A map with a topographic style.
        let map: Map = {
            let map = Map(basemapStyle: .arcGISTopographic)
            return map
        }()

        /// A service that fetches the raster using image source url.
        let imageServiceRaster: ImageServiceRaster = {
            let serviceRaster = ImageServiceRaster(
                url: .imageServiceURL
            )
            serviceRaster.mosaicRule = MosaicRule()
            return serviceRaster
        }()

        /// A computed property returns center of raster so that map recenters on rule change.
        var imageServiceRasterCenter: Point {
            imageServiceRaster.serviceInfo?.fullExtent?.center ?? Point(x: 0, y: 0)
        }

        init() {
            let rasterLayer = RasterLayer(raster: imageServiceRaster)
            map.addOperationalLayer(rasterLayer)
        }
    }
}

private extension URL {
    /// This sample uses a raster image service that shows aerial images of Amberg, Germany.
    static let imageServiceURL = URL(string: "https://sampleserver7.arcgisonline.com/server/rest/services/amberg_germany/ImageServer")!
}

#Preview {
    NavigationStack {
        ApplyMosaicRuleToRastersView()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.