def xform(extent, srcCRS, destCRS): if srcCRS == destCRS: return extent # nothing to do # cut down the extent so it's not too big # clamped to the projection's valid area (usually small) projectionClampedExtent = clampToProjectionExtent(extent, srcCRS) # clamped to the world (might not work in some projections) worldClampedExtent = clampToWorld(extent, srcCRS) # xform the two extents to the dest CRS transform = QgsCoordinateTransform(srcCRS, destCRS, QgsProject.instance()) xformed_projectionClamped = QgsRectangle() # null rect if not projectionClampedExtent.isNull(): xformed_projectionClamped = transform.transformBoundingBox(projectionClampedExtent) xformed_worldClamped = QgsRectangle() # null rect if not worldClampedExtent.isNull(): xformed_worldClamped = transform.transformBoundingBox(worldClampedExtent) # make final choice of what to use # we WANT to use the world one, but sometimes cannot # indicates everything is ok -- likely no projection blowing up if xformed_worldClamped.contains(xformed_projectionClamped): return xformed_worldClamped # likely good # if one is null, return the other if xformed_projectionClamped.isNull(): return xformed_worldClamped if xformed_worldClamped.isNull(): return xformed_projectionClamped # clamp to the destination CRS (last resort to try to get something valid) return clampToProjectionExtent(xformed_worldClamped, destCRS)