本文整理汇总了Python中qgis.core.QgsRectangle类的典型用法代码示例。如果您正苦于以下问题:Python QgsRectangle类的具体用法?Python QgsRectangle怎么用?Python QgsRectangle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QgsRectangle类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: testAsWktPolygon
def testAsWktPolygon(self):
"""Test that we can get a proper rect wkt polygon representation for rect"""
rect1 = QgsRectangle(0.0, 0.0, 5.0, 5.0)
myExpectedWkt = "POLYGON((0 0, " "5 0, " "5 5, " "0 5, " "0 0))"
myWkt = rect1.asWktPolygon()
myMessage = "Expected: %s\nGot: %s\n" % (myExpectedWkt, myWkt)
assert compareWkt(myWkt, myExpectedWkt), myMessage
开发者ID:dwadler,项目名称:QGIS,代码行数:7,代码来源:test_qgsrectangle.py
示例2: bounds
def bounds(self):
"""
Function for recalculating the bounded extents of the
layers as they are processed. Under construction
:return:
"""
# Requires refinement for raster manipulation of bounds
selected_extent = unicode(self.getParameterValue(self.MAP_EXTENT)).split(',')
xMin = float(selected_extent[0])
xMax = float(selected_extent[1])
yMin = float(selected_extent[2])
yMax = float(selected_extent[3])
extent = QgsRectangle(xMin, yMin, xMax, yMax)
mapCRS = iface.mapCanvas().mapSettings().destinationCrs()
transform = QgsCoordinateTransform(
mapCRS,
QgsCoordinateReferenceSystem('EPSG:4326') # WGS84
# QgsCoordinateReferenceSystem('EPSG:3785') # Popular vis mercator
)
try:
layer_extent = transform.transform(extent)
except QgsCsException:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
"exception in transform layer srs")
layer_extent = QgsRectangle(-180, -90, 180, 90)
ProcessingLog.addToLog(ProcessingLog.LOG_INFO, layer_extent.toString())
return layer_extent
开发者ID:SpatialVision,项目名称:QGIS2GISCloud_Publisher,代码行数:32,代码来源:giscloud_uploader_algorithm.py
示例3: testAsWktCoordinates
def testAsWktCoordinates(self):
"""Test that we can get a proper wkt representation fo the rect"""
rect1 = QgsRectangle(0.0, 0.0, 5.0, 5.0)
myExpectedWkt = "0 0, " "5 5"
myWkt = rect1.asWktCoordinates()
myMessage = "Expected: %s\nGot: %s\n" % (myExpectedWkt, myWkt)
assert compareWkt(myWkt, myExpectedWkt), myMessage
开发者ID:dwadler,项目名称:QGIS,代码行数:7,代码来源:test_qgsrectangle.py
示例4: getBBox
def getBBox(self, item):
ogrFeature = item.data(Qt.UserRole)
geom = QgsGeometry.fromWkt(ogrFeature.GetGeometryRef().ExportToWkt())
if (ogrFeature.GetDefnRef().GetGeomType() == ogr.wkbPoint):
mapextent = self.plugin.canvas.extent()
ww = mapextent.width()/100
mapcrs = self.plugin.canvas.mapSettings().destinationCrs()
x = geom.boundingBox().center().x()
y = geom.boundingBox().center().y()
ww = 50.0
if mapcrs.mapUnits() == QgsUnitTypes.DistanceFeet:
ww = 150
if mapcrs.mapUnits() == QgsUnitTypes.DistanceDegrees:
ww = 0.0005
bbox = QgsRectangle(x-10*ww, y-10*ww, x+10*ww, y+10*ww)
return bbox
else:
bbox = geom.boundingBox()
rubberRect = QgsRectangle(bbox.xMinimum(), bbox.yMinimum(),
bbox.xMaximum(), bbox.yMaximum())
return rubberRect
开发者ID:xcaeag,项目名称:Nominatim-Qgis-Plugin,代码行数:25,代码来源:nominatim_dlg.py
示例5: test_mouse_drag
def test_mouse_drag(self):
"""Test setting extents by dragging works.
This currently fails as QTest does not properly do the mouse
interactions with the canvas.
"""
# Imported here because it is not available in OSX QGIS bundle
# pylint: disable=redefined-outer-name
from PyQt4.QtTest import QTest
# Click the capture button
QTest.mouseClick(self.dialog.capture_button, Qt.LeftButton)
# drag a rect on the canvas
QTest.mousePress(CANVAS, Qt.LeftButton, pos=QPoint(0, 0), delay=500)
QTest.mouseRelease(
CANVAS, Qt.LeftButton,
pos=QPoint(300, 300),
delay=-1)
# on drag the extents selector windows should appear again
QTest.qWaitForWindowShown(self.dialog)
# Click ok to dispose of the window again
ok = self.dialog.button_box.button(QtGui.QDialogButtonBox.Ok)
QTest.mouseClick(ok, Qt.LeftButton)
# Check the extent emitted on closing teh dialog is correct
expected_extent = QgsRectangle(10.0, 10.0, 30.0, 20.0)
self.assertEqual(self.extent.toString(), expected_extent.toString())
开发者ID:Mloweedgar,项目名称:inasafe,代码行数:30,代码来源:test_extent_selector.py
示例6: layer_value
def layer_value(feature, layer, defaultconfig):
layername = defaultconfig['layer']
expression = defaultconfig['expression']
field = defaultconfig['field']
searchlayer = QgsMapLayerRegistry.instance().mapLayersByName(layername)[0]
if feature.geometry():
rect = feature.geometry().boundingBox()
if layer.geometryType() == QGis.Point:
point = feature.geometry().asPoint()
rect = QgsRectangle(point.x(), point.y(), point.x() + 10, point.y() + 10)
else:
rect.scale(20)
rect = canvas.mapRenderer().mapToLayerCoordinates(layer, rect)
rq = QgsFeatureRequest().setFilterRect(rect)\
.setFlags(QgsFeatureRequest.ExactIntersect)
features = searchlayer.getFeatures(rq)
else:
features = searchlayer.getFeatures()
exp = QgsExpression(expression)
exp.prepare(searchlayer.pendingFields())
for f in features:
if exp.evaluate(f):
return f[field]
raise DefaultError('No features found')
开发者ID:HeatherHillers,项目名称:Roam,代码行数:29,代码来源:defaults.py
示例7: initRotation
def initRotation(self, boundBox):
# calculate rotation parameters..interpreted from affine transformation plugin
anchorPoint = boundBox.center()
# We convert the angle from degree to radiant
rad = self.angle.value() * math.pi / 180.0
a = math.cos(rad)
b = -1 * math.sin(rad)
c = anchorPoint.x() - math.cos(rad) * anchorPoint.x() + math.sin(rad) * anchorPoint.y()
d = math.sin(rad)
e = math.cos(rad)
f = anchorPoint.y() - math.sin(rad) * anchorPoint.x() - math.cos(rad) * anchorPoint.y()
self.rotationParams = (a, b, c, d, e, f)
# Rotate the bounding box to set a new extent
ptMin = QgsPoint(boundBox.xMinimum(), boundBox.yMinimum())
ptMax = QgsPoint(boundBox.xMaximum(), boundBox.yMaximum())
self.rotatePoint(ptMin)
self.rotatePoint(ptMax)
newBoundBox = QgsRectangle(ptMin, ptMax)
newBoundBox.combineExtentWith(boundBox)
return newBoundBox
开发者ID:HeatherHillers,项目名称:QGIS,代码行数:27,代码来源:doVectorGrid.py
示例8: update_extent
def update_extent(self, extent):
"""Update extent value in GUI based from an extent.
:param extent: A list in the form [xmin, ymin, xmax, ymax] where all
coordinates provided are in Geographic / EPSG:4326.
:type extent: list
"""
self.x_minimum.setValue(extent[0])
self.y_minimum.setValue(extent[1])
self.x_maximum.setValue(extent[2])
self.y_maximum.setValue(extent[3])
# Updating the country if possible.
rectangle = QgsRectangle(extent[0], extent[1], extent[2], extent[3])
center = rectangle.center()
for country in self.bbox_countries:
for polygon in self.bbox_countries[country]:
if polygon.contains(center):
index = self.country_comboBox.findText(country)
self.country_comboBox.setCurrentIndex(index)
break
else:
# Continue if the inner loop wasn't broken.
continue
# Inner loop was broken, break the outer.
break
else:
self.country_comboBox.setCurrentIndex(0)
开发者ID:ismailsunni,项目名称:inasafe,代码行数:29,代码来源:osm_downloader_dialog.py
示例9: testOperators
def testOperators(self):
rect1 = QgsRectangle(10, 20, 40, 40)
rect2 = rect1 + QgsVector(3, 5.5)
assert rect2 == QgsRectangle(13, 25.5, 43, 45.5), "QgsRectangle + operator does no work"
# Subtracting the center point, so it becomes zero.
rect1 -= rect1.center() - QgsPointXY(0, 0)
assert rect1.center() == QgsPointXY(0, 0)
开发者ID:phborba,项目名称:QGIS,代码行数:8,代码来源:test_qgsrectangle.py
示例10: testAsWktCoordinates
def testAsWktCoordinates(self):
"""Test that we can get a proper wkt representation fo the rect"""
rect1 = QgsRectangle( 0.0, 0.0, 5.0, 5.0)
myExpectedWkt = '0.0000000000000000 0.0000000000000000, 5.0000000000000000 5.0000000000000000'
myWkt = rect1.asWktCoordinates()
myMessage = ('Expected: %s\nGot: %s\n' %
(myExpectedWkt, myWkt))
self.assertEquals(myWkt, myExpectedWkt, myMessage)
开发者ID:mokerjoke,项目名称:Quantum-GIS,代码行数:8,代码来源:test_qgsrectangle.py
示例11: processAlgorithm
def processAlgorithm(self, progress):
idx = self.getParameterValue(self.TYPE)
extent = self.getParameterValue(self.EXTENT).split(',')
hSpacing = self.getParameterValue(self.HSPACING)
vSpacing = self.getParameterValue(self.VSPACING)
crs = QgsCoordinateReferenceSystem(self.getParameterValue(self.CRS))
bbox = QgsRectangle(float(extent[0]), float(extent[2]),
float(extent[1]), float(extent[3]))
width = bbox.width()
height = bbox.height()
centerX = bbox.center().x()
centerY = bbox.center().y()
originX = centerX - width / 2.0
originY = centerY - height / 2.0
if hSpacing <= 0 or vSpacing <= 0:
raise GeoAlgorithmExecutionException(
self.tr('Invalid grid spacing: %s/%s' % (hSpacing, vSpacing)))
if width < hSpacing:
raise GeoAlgorithmExecutionException(
self.tr('Horizontal spacing is too small for the covered area'))
if height < vSpacing:
raise GeoAlgorithmExecutionException(
self.tr('Vertical spacing is too small for the covered area'))
if self.TYPES[idx].find('polygon') >= 0:
geometryType = QGis.WKBPolygon
else:
geometryType = QGis.WKBLineString
fields = [QgsField('left', QVariant.Double, '', 24, 16),
QgsField('top', QVariant.Double, '', 24, 16),
QgsField('right', QVariant.Double, '', 24, 16),
QgsField('bottom', QVariant.Double, '', 24, 16)
]
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields,
geometryType, crs)
if idx == 0:
self._rectangleGridLine(
writer, width, height, originX, originY, hSpacing, vSpacing)
elif idx == 1:
self._rectangleGridPoly(
writer, width, height, originX, originY, hSpacing, vSpacing)
elif idx == 2:
self._diamondGrid(
writer, width, height, originX, originY, hSpacing, vSpacing)
elif idx == 3:
self._hexagonGrid(
writer, width, height, originX, originY, hSpacing, vSpacing)
del writer
开发者ID:redwoodxiao,项目名称:QGIS,代码行数:57,代码来源:Grid.py
示例12: testToBox3d
def testToBox3d(self):
rect = QgsRectangle(0, 0.1, 0.2, 0.3)
box = rect.toBox3d(0.4, 0.5)
self.assertEqual(box.xMinimum(), 0.0)
self.assertEqual(box.yMinimum(), 0.1)
self.assertEqual(box.zMinimum(), 0.4)
self.assertEqual(box.xMaximum(), 0.2)
self.assertEqual(box.yMaximum(), 0.3)
self.assertEqual(box.zMaximum(), 0.5)
开发者ID:phborba,项目名称:QGIS,代码行数:9,代码来源:test_qgsrectangle.py
示例13: _rect
def _rect(self, startPoint, endPoint):
if startPoint is None or endPoint is None:
return None
p0 = self.toCanvasCoordinates(startPoint)
p1 = self.toCanvasCoordinates(endPoint)
canvas_rect = QgsRectangle(QgsPoint(p0.x(), p0.y()), QgsPoint(p1.x(), p1.y()))
center = QgsPoint((startPoint.x() + endPoint.x()) / 2, (startPoint.y() + endPoint.y()) / 2)
return RotatedRect(center, self.mupp * canvas_rect.width(), self.mupp * canvas_rect.height()).rotate(self.rotation, center)
开发者ID:biapar,项目名称:Qgis2threejs,代码行数:9,代码来源:qgis2threejsdialog.py
示例14: preview
def preview(request, layer_slug):
"""Home page for layers.
:param request: The web request.
:param layer_slug: The layer
"""
layer = get_object_or_404(Layer, slug=layer_slug)
layer_path = os.path.join(
settings.MEDIA_ROOT, 'layers', layer.slug, 'raw')
map_layer = QgsVectorLayer(layer_path, layer.name, 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(map_layer)
layer_uri = tempfile.NamedTemporaryFile(
suffix='.png', prefix='inasafe-web-', dir='/tmp/').name
# create image
image = QImage(QSize(100, 100), QImage.Format_ARGB32_Premultiplied)
# set image's background color
color = QColor(255, 255, 255)
image.fill(color.rgb())
# create painter
p = QPainter()
p.begin(image)
p.setRenderHint(QPainter.Antialiasing)
renderer = QgsMapRenderer()
# set layer set
layers = [map_layer.id()] # add ID of every layer
renderer.setLayerSet(layers)
# set extent
rect = QgsRectangle(renderer.fullExtent())
rect.scale(1.1)
renderer.setExtent(rect)
# set output size
renderer.setOutputSize(image.size(), image.logicalDpiX())
# do the rendering
renderer.render(p)
p.end()
# clean up
registry_list = qgis_layers()
QgsMapLayerRegistry.instance().removeMapLayer(map_layer.id())
print registry_list
# save image
image.save(layer_uri, 'png')
with open(layer_uri, 'rb') as f:
response = HttpResponse(f.read(), content_type='png')
os.remove(layer_uri)
return response
开发者ID:mbernasocchi,项目名称:webandgis,代码行数:57,代码来源:views.py
示例15: _populate_bookmarks_list
def _populate_bookmarks_list(self):
"""Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are reprojected to mapcanvas crs.
"""
# Connect to the QGIS sqlite database and check if the table exists.
# noinspection PyArgumentList
db_file_path = QgsApplication.qgisUserDatabaseFilePath()
db = sqlite3.connect(db_file_path)
cursor = db.cursor()
cursor.execute(
'SELECT COUNT(*) '
'FROM sqlite_master '
'WHERE type=\'table\' '
'AND name=\'tbl_bookmarks\';')
number_of_rows = cursor.fetchone()[0]
if number_of_rows > 0:
cursor.execute(
'SELECT * '
'FROM tbl_bookmarks;')
bookmarks = cursor.fetchall()
canvas_crs = self.canvas.mapSettings().destinationCrs()
for bookmark in bookmarks:
name = bookmark[1]
srid = bookmark[7]
rectangle = QgsRectangle(
bookmark[3], bookmark[4], bookmark[5], bookmark[6])
if srid != canvas_crs.srsid():
transform = QgsCoordinateTransform(
QgsCoordinateReferenceSystem(srid),
canvas_crs,
QgsProject.instance()
)
try:
rectangle = transform.transform(rectangle)
except QgsCsException:
rectangle = QgsRectangle()
if rectangle.isEmpty():
pass
self.bookmarks_list.addItem(name, rectangle)
if self.bookmarks_list.currentIndex() >= 0:
self.create_bookmarks_label.hide()
else:
self.create_bookmarks_label.show()
self.hazard_exposure_bookmark.setDisabled(True)
self.bookmarks_list.hide()
开发者ID:inasafe,项目名称:inasafe,代码行数:56,代码来源:extent_selector_dialog.py
示例16: rect
def rect(self):
if self.calculatedRect:
return self.calculatedRect
if len(self.quads) == 0:
return QgsRectangle()
rect = QgsRectangle(self.quads[0].rect)
for quad in self.quads[1:]:
rect.unionRect(quad.rect)
self.calculatedRect = rect
return rect
开发者ID:HydroLogic,项目名称:Qgis2threejs,代码行数:10,代码来源:quadtree.py
示例17: test_point_to_rectangle
def test_point_to_rectangle(self):
"""Test for point to rectangle."""
point = QgsPoint(1.0, 1.0)
rectangle = point_to_rectangle(point)
expected_rectangle = QgsRectangle(
0.9999999999900000,
0.9999999999900000,
1.0000000000100000,
1.0000000000100000)
self.assertEqual(rectangle.toString(), expected_rectangle.toString())
开发者ID:kartoza,项目名称:sg-diagram-downloader,代码行数:10,代码来源:test_sg_utilities.py
示例18: testGetClickBbox
def testGetClickBbox(self):
"""
Tests that a click returns a small bbox.
"""
# pixel coords for fake click
self.prepareTestCanvas()
myPoint = QgsPoint(50, 15)
myBox = self.bucketFill.getClickBbox(myPoint)
myExpectedBox = QgsRectangle(49.99850465,
14.99850465,
50.00149535,
15.00149535)
myMessage = ('Bounding box was incorrect. Received values %s'
' Expected values %s' % (
str('%s, %s, %s, %s' % (
myBox.xMinimum(), myBox.yMinimum(),
myBox.xMaximum(), myBox.yMaximum()
)),
str('%s, %s, %s, %s' % (
myExpectedBox.xMinimum(), myExpectedBox.yMinimum(),
myExpectedBox.xMaximum(), myExpectedBox.yMaximum()
))
))
assert (round(myBox.xMinimum(), 9) ==
round(myExpectedBox.xMinimum(), 9) and
round(myBox.xMaximum(), 9) ==
round(myExpectedBox.xMaximum(), 9) and
round(myBox.yMinimum(), 9) ==
round(myExpectedBox.yMinimum(), 9) and
round(myBox.yMaximum(), 9) ==
round(myExpectedBox.yMaximum(), 9)), myMessage
开发者ID:rudithiede,项目名称:QGIS-Bucket-Fill,代码行数:31,代码来源:test_bucketfill.py
示例19: getClickBbox
def getClickBbox(self, thePoint):
"""
Get a tiny bbox around a mouse click.
Args:
Point object.
Returns:
Tiny QgsRectangle bbox around point.
Raises:
CoordinateProcessingException if bbox creation encounters error.
"""
# get the xy coords
#QMessageBox.information(None, 'VF', str(thePoint))
myX = thePoint.x()
myY = thePoint.y()
myUnitsPerPixel = self.canvas.mapUnitsPerPixel()
# create a little bbox from clicked coords
try:
myBbox = QgsRectangle()
myBbox.setXMinimum(myX - myUnitsPerPixel)
myBbox.setYMinimum(myY - myUnitsPerPixel)
myBbox.setXMaximum(myX + myUnitsPerPixel)
myBbox.setYMaximum(myY + myUnitsPerPixel)
#QMessageBox.information(None, 'VF', myBbox.toString())
return myBbox
except:
msg = 'Click coordinates could not be processed.'
raise ex.CoordinateProcessingException(msg)
开发者ID:rudithiede,项目名称:QGIS-Bucket-Fill,代码行数:30,代码来源:bucketfill.py
示例20: layer_value
def layer_value(feature, layer, defaultconfig):
if not canvas:
roam.utils.warning("No canvas set for using layer_values default function")
return None
layers = []
# layer name can also be a list of layers to search
layername = defaultconfig['layer']
if isinstance(layername, basestring):
layers.append(layername)
else:
layers = layername
expression = defaultconfig['expression']
field = defaultconfig['field']
for searchlayer in layers:
try:
searchlayer = QgsMapLayerRegistry.instance().mapLayersByName(searchlayer)[0]
except IndexError:
RoamEvents.raisemessage("Missing layer",
"Unable to find layer used in widget expression {}".format(searchlayer),
level=1)
roam.utils.warning("Unable to find expression layer {}".format(searchlayer))
return
if feature.geometry():
rect = feature.geometry().boundingBox()
if layer.geometryType() == QGis.Point:
point = feature.geometry().asPoint()
rect = QgsRectangle(point.x(), point.y(), point.x() + 10, point.y() + 10)
rect.scale(20)
rect = canvas.mapRenderer().mapToLayerCoordinates(layer, rect)
rq = QgsFeatureRequest().setFilterRect(rect)\
.setFlags(QgsFeatureRequest.ExactIntersect)
features = searchlayer.getFeatures(rq)
else:
features = searchlayer.getFeatures()
exp = QgsExpression(expression)
exp.prepare(searchlayer.pendingFields())
if exp.hasParserError():
error = exp.parserErrorString()
roam.utils.warning(error)
for f in features:
value = exp.evaluate(f)
if exp.hasEvalError():
error = exp.evalErrorString()
roam.utils.warning(error)
if value:
return f[field]
raise DefaultError('No features found')
开发者ID:nicklv,项目名称:Roam,代码行数:54,代码来源:defaults.py
注:本文中的qgis.core.QgsRectangle类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论