Build and delete raster pyramids to compare the display performance of a raster.

Use case
Raster pyramids improve display performance by storing progressively lower-resolution versions of a raster dataset. They allow the resolution appropriate for the display scale to be read instead of repeatedly resampling the full-resolution raster. For example, a field worker viewing a raster offline can preemptively build pyramids once to make subsequent navigation more responsive. Building pyramids takes time and additional disk space, but those costs can be offset by faster display when the map is viewed at different scales.
A hybrid raster format (such as geospatial PDF) containing vector data can particularly benefit from pyramids, because the vector data otherwise needs to be rasterized as the display scale changes.
How to use the sample
The sample initially displays a geospatial PDF raster without pyramids. Pan and zoom to observe its display performance.
Tap the Build button and wait for the build to complete. Pan and zoom again to compare the performance of the raster with pyramids.
Tap the Delete button to delete the pyramids and recreate the raster layer without them. Repeat the same navigation to compare the two states.
Tap the Zoom button to set the viewpoint to the various pyramid levels, or the raster’s native resolution when the pyramids aren’t built.
How it works
- Create and load a geospatial PDF
Rasterfrom the local file. - Create a
RasterLayerfrom the raster, add it to the map’s operational layers, and set the initial viewpoint to its extent. - Get the
pyramidsproperty after loading the raster.- Use
RasterPyramids.activeBuildOperationto determine if an operation is already running.
- Use
- When the Build button is tapped, create
BuildRasterPyramidsParametersand call theRasterPyramids.build(using:)method.- Start a
BuildRasterPyramidsOperationthat generates raster pyramid files alongside the raster file. - Wait for the operation to complete.
- A successful
resultcontainsRasterPyramidInfoabout the pyramid set that was built. - If the operation fails or is canceled, the corresponding error is reported.
- A successful
- Start a
- When the Delete button is tapped, call the
RasterPyramids.delete()method to remove the external pyramids. Recreate and re-add the raster layer.
Relevant API
- BuildRasterPyramidsOperation
- BuildRasterPyramidsParameters
- Raster
- RasterLayer
- RasterPyramidInfo
- RasterPyramids
About the data
The sample uses an open-source Park Map - Yosemite National Park geospatial PDF containing vector cartography and raster to show the various features of Yosemite.
Additional information
Pyramids only need to be built once for a raster dataset and can be reused when the raster is opened again. This sample allows deleting the pyramids to demonstrate the performance difference. The raster pyramids APIs build and delete external .ovr pyramid files; they do not delete embedded pyramids within the raster.
For more information, see:
- Build and manage raster pyramids on Esri Developer website
- Raster pyramids in the ArcGIS Pro documentation
Tags
GeoPDF, geospatial PDF, image, offline, optimization, overview, PDF, performance, pyramids, raster, vector
Sample code
// Copyright 2026 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 ArcGISimport SwiftUI
struct BuildRasterPyramidsView: View { /// The model that manages the raster and its build pyramids operation. @State private var model = Model() /// A Boolean value indicating whether the pyramid level stepper is visible. @State private var showsLevelStepper = false /// The value of the stepper. @State private var stepperValue = 0 /// The current draw status of the map view. @State private var drawStatus: DrawStatus = .inProgress /// The map view's size for calculating a full-resolution viewpoint. @State private var viewSize: CGSize? /// The center of the current map viewpoint. @State private var viewpointCenter: Point? /// The error that occurred during raster pyramid operations. @State private var error: (any Error)? /// The status of the sample. @State private var status: State = .loading
/// A Boolean value indicating whether the sample is performing an action. private var isBusy: Bool { switch status { case .loading, .building: true case .built, .notBuilt, .failed: false } }
/// The pyramid level for calculation. Zero represents full resolution. private var pyramidLevel: Int { // The pyramid level is the inverse of the stepper value, i.e., // the stepper shows the full resolution as the maximum value. model.levelCount - stepperValue }
var body: some View { MapViewReader { mapView in MapView(map: model.map) .onViewpointChanged(kind: .centerAndScale) { newViewpoint in viewpointCenter = newViewpoint.targetGeometry as? Point } .onDrawStatusChanged { newDrawStatus in withAnimation { drawStatus = newDrawStatus } } .interactionModes(isBusy ? [] : .all) .onGeometryChange(for: CGSize.self, of: \.size) { newSize in viewSize = newSize } .overlay(alignment: .top) { Text("Status: \(Text(status.message).italic())") .frame(maxWidth: .infinity) .padding(.vertical, 6) .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal) } .toolbar { let toolbarItem = ToolbarItem(placement: .bottomBar) { if let operation = model.pyramids?.activeBuildOperation { ProgressView(operation.progress) .progressViewStyle(.gauge) } else if drawStatus == .inProgress || isBusy { ProgressView() } else { Image(systemName: "checkmark.circle") .foregroundStyle(.green) } } if #available(iOS 26.0, *) { toolbarItem .sharedBackgroundVisibility(.hidden) } else { toolbarItem } ToolbarItemGroup(placement: .bottomBar) { Spacer()
// A button to show or hide the pyramid level stepper. Button( "Zoom", systemImage: "arrow.up.left.and.down.right.magnifyingglass" ) { showsLevelStepper = true Task { await setViewpoint(pyramidLevel: pyramidLevel, mapView: mapView) } } .labelStyle(.iconOnly) .onChange(of: model.levelCount) { _, newLevelCount in stepperValue = min(stepperValue, newLevelCount) } .disabled(drawStatus == .inProgress || isBusy || viewSize == nil) .popover(isPresented: $showsLevelStepper) { Group { if model.levelCount > 0 { Stepper( value: $stepperValue, in: 0...model.levelCount, step: 1 ) { Text("Pyramid level: \(pyramidLevel)") } .onChange(of: stepperValue) { Task { await setViewpoint(pyramidLevel: pyramidLevel, mapView: mapView) } } .disabled(isBusy) } else { VStack { Text("Pyramid level: \(stepperValue)") Text("Zoomed to full resolution. Build pyramids to enable levels.") .font(.caption) } } } .padding() .frame(idealWidth: 320) .presentationBackground(.thinMaterial) .presentationCompactAdaptation(.popover) }
Spacer()
// Buttons to build or delete the raster pyramids. if status == .built { Button("Delete") { do { try model.deletePyramids() status = .notBuilt(additionalInfo: "Ready") } catch { status = .failed(details: "Failed to delete pyramids, \(error.localizedDescription)") } } .disabled(drawStatus == .inProgress || !model.canDelete) } else { Button("Build") { Task { do { status = .building try await model.buildPyramids() status = .built } catch { status = .failed(details: "Failed to build pyramids, \(error.localizedDescription)") } } } .disabled(drawStatus == .inProgress || !model.canBuild) } } } .errorAlert(presentingError: $error) .task { do { status = .loading try await model.setUp() if let initialViewpoint = model.initialViewpoint { await mapView.setViewpoint(initialViewpoint) } } catch { status = .failed(details: "Failed to load raster, \(error.localizedDescription)") return } if let pyramids = model.pyramids { if let info = pyramids.info { if info.isEmbedded { // Pyramids can be embedded in the source raster // dataset or stored in a separate pyramid file // (.ovr). We cannot build pyramids for a raster // if the pyramids are embedded. status = .notBuilt(additionalInfo: "Embedded") } else if info.fileURL != nil { // If the pyramids are not embedded, and the // file path is not nil, then the pyramids are // built. status = .built } else { fatalError("Unexpected state: pyramids.info is not-nil but pyramids aren't built or embedded.") } } else { status = .notBuilt(additionalInfo: "Ready") } } else { // This property is nil until the raster is loaded. // After the raster is loaded, this property is non-nil for // file-based rasters that supports pyramids. status = .notBuilt(additionalInfo: "Doesn't support pyramid") } } } }
/// Sets the map view's viewpoint to the requested pyramid level. /// - Parameters: /// - level: The pyramid level. /// - mapView: The map view to set the viewpoint. private func setViewpoint(pyramidLevel level: Int, mapView: MapViewProxy) async { guard let viewSize, let viewpointCenter, let viewpoint = model.makeViewpoint( viewSize: viewSize, level: level, center: viewpointCenter ) else { return } await mapView.setViewpoint(viewpoint) }
/// The state of the sample. private enum State: Equatable { case loading case building case built case notBuilt(additionalInfo: String) case failed(details: String)
/// The status text for the model. var message: String { switch self { case .loading: "Loading raster" case .building: "Building pyramids" case .built: "Pyramids built" case .notBuilt(let additionalInfo): "Pyramids not built: \(additionalInfo)" case .failed(let details): "Failure: \(details)" } } }}
/// A circular gauge progress view style.private struct GaugeProgressViewStyle: ProgressViewStyle { func makeBody(configuration: Configuration) -> some View { if let fractionCompleted = configuration.fractionCompleted { let gradientStops: [Gradient.Stop] = [ .init(color: .accent, location: 0), .init(color: .accent, location: fractionCompleted), .init(color: .init(.tertiarySystemFill), location: fractionCompleted), .init(color: .init(.tertiarySystemFill), location: 1) ] let gradient = AngularGradient(gradient: .init(stops: gradientStops), center: .center)
Image(systemName: "circle.fill") .foregroundStyle(gradient) .rotationEffect(.degrees(-90)) } }}
private extension ProgressViewStyle where Self == GaugeProgressViewStyle { /// A progress view that visually indicates its progress with a gauge. static var gauge: Self { .init() }}// Copyright 2026 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 ArcGISimport Foundationimport Observation
extension BuildRasterPyramidsView { @Observable final class Model { /// A map with light gray basemap and a raster layer. let map = Map(basemapStyle: .arcGISLightGrayBase) /// The directory that contains the raster and its pyramids. private let temporaryDirectory = FileManager.default.temporaryDirectory .appending( component: ProcessInfo.processInfo.globallyUniqueString, directoryHint: .isDirectory ) /// The raster for building pyramids. @ObservationIgnored private var raster: Raster? /// The raster layer. @ObservationIgnored private var layer: RasterLayer? /// The initial viewpoint for the map view. @ObservationIgnored private(set) var initialViewpoint: Viewpoint?
/// The raster pyramids for the raster. var pyramids: RasterPyramids? { raster?.pyramids }
/// The number of pyramid levels. var levelCount: Int { pyramids?.info?.levelCount ?? 0 }
/// A Boolean value indicating whether the build pyramids operation /// can start. var canBuild: Bool { guard let pyramids, pyramids.info == nil, pyramids.activeBuildOperation == nil else { // Don't build if the pyramids already exist, or there is an // active build operation. return false } return true }
/// A Boolean value indicating whether the pyramids can be deleted. var canDelete: Bool { guard let pyramids, let info = pyramids.info, !info.isEmbedded, pyramids.activeBuildOperation == nil else { // Don't delete if the pyramids don't exist, are embedded in the // raster, or there is an active build operation. return false } return true }
init() { try? FileManager.default.createDirectory( at: temporaryDirectory, withIntermediateDirectories: true ) }
/// Sets up the model. @MainActor func setUp() async throws { let destination = temporaryDirectory.appending(path: URL.yosemiteGeoPDF.lastPathComponent) try FileManager.default.copyItem(at: .yosemiteGeoPDF, to: destination) let raster = Raster(fileURL: destination) let layer = RasterLayer(raster: raster) try await layer.load() self.raster = raster self.layer = layer map.addOperationalLayer(layer) if let extent = layer.fullExtent { initialViewpoint = Viewpoint(boundingGeometry: extent) } }
/// Creates a viewpoint at the current map center and requested level. /// - Parameters: /// - viewSize: The size of the map view. /// - level: The pyramid level; zero for full resolution. /// - center: The current map viewpoint's center. /// - Returns: A viewpoint, or `nil` if the level is invalid. func makeViewpoint(viewSize: CGSize, level: Int, center: Point) -> Viewpoint? { guard (0...levelCount).contains(level), let layer, layer.loadStatus == .loaded, let spatialReference = layer.fullExtent?.spatialReference, let center = GeometryEngine.project(center, into: spatialReference), let info = raster?.info else { return nil } let scale = Double(1 << level) let width = viewSize.width * info.cellSizeX * scale let height = viewSize.height * info.cellSizeY * scale guard width > 0, height > 0 else { return nil } return Viewpoint( boundingGeometry: Envelope( center: center, width: width, height: height ) ) }
/// Builds the pyramids for the raster. @MainActor func buildPyramids() async throws { guard let pyramids else { return } // You can customize the parameters. The default parameters are used // here for simplicity. let parameters = BuildRasterPyramidsParameters() let operation = try pyramids.build(using: parameters) _ = try await operation.result }
/// Deletes the pyramids for the owning raster. func deletePyramids() throws { guard let pyramids else { return } try pyramids.delete() }
deinit { if let buildOperation = pyramids?.activeBuildOperation { buildOperation.cancel() } if let raster = raster.take() { raster.close() } try? FileManager.default.removeItem(at: temporaryDirectory) } }}
private extension URL { /// The URL for the Yosemite geospatial PDF raster. static var yosemiteGeoPDF: URL { Bundle.main.url(forResource: "YOSE_ParkMap", withExtension: "pdf")! }}