Skip to main content

applyStyleItem

汇总

可通过 TextElement 对象访问属性和方法,这些属性和方法用于管理布局上或地图图形图层中的文本元素。

讨论

TextElement 对象表示在布局上或地图图形图层中插入的文本。 其中包括文本、注释、矩形文本、标题等项目。 不包括作为图例、表格框或其他地图整饰元素一部分的文本字符串。 Layout 对象上的 listElements 方法将返回页面布局元素对象的 Python 列表。 然后,您必须迭代列表中的每个项目或指定一个索引编号以引用特定的页面元素对象。 如要仅返回 TextElement 对象的列表,请为 elementType 参数使用 TEXT_ELEMENT 常量。 还可以使用 wildcard 值,基于元素的 name 值对搜索进行进一步优化。 为每个文本元素提供唯一名称,以便轻松地引用元素。

可以通过两种方法创建文本元素。 第一个方法是 ArcGISProject 对象上的 createTextElement 方法,您可以使用 PointPolygonPolyline 几何在布局或图形图层中创建一个文本元素。 第二个方法是使用 TextElement 对象的 clone 方法克隆现有文本元素。 此方法十分有用,因为在某些情况下,从现有元素开始操作会更加容易。 克隆元素时,请提供 suffix 值以使克隆的元素后续可以通过 listElements 方法使用通配符和相同的 suffix 值进行识别。 可以使用 delete 方法进一步修改或删除返回的元素列表。

elementPositionXelementPositionY 值取决于元素的锚点位置,该位置在 ArcGIS Pro 中的 格式 选项卡上设置。 可以使用 setAnchor 方法修改锚点位置。 了解 elementRotationtextAngle 属性之间的差异十分重要。 建议以插入矩形文本为例。 elementRotation 属性控制矩形的旋转,而 textAngle 属性控制矩形内文本的角度。 对于点文本,无论设置何种属性,这两个值均将进行同步。

文本元素具有 getDefinitionsetDefinition 方法,可用于修改未向 TextElement 类暴露的附加属性。 有关详细信息,请参阅 Python CIM 访问 帮助主题。

语法

applyStyleItem()

属性

名称 说明 数据类型

anchor

(只读)

返回表示当前锚点位置的以下字符串值之一。 要更改值,请使用 setAnchor 方法。

  • BOTTOM_LEFT_CORNER—当前锚点位置是左下角位置。

  • BOTTOM_MID_POINT—当前锚点位置是底部中央位置。

  • BOTTOM_RIGHT_CORNER—当前锚点位置是右下角位置。

  • CENTER_POINT—当前锚点位置是中央位置。

  • LEFT_MID_POINT—当前锚点位置是左侧中央位置。

  • RIGHT_MID_POINT—当前锚点位置是右侧中央位置。

  • TOP_LEFT_CORNER—当前锚点位置是左上角位置。

  • TOP_MID_POINT—当前锚点位置是顶部中央位置。

  • TOP_RIGHT_CORNER—当前锚点位置是右上角位置。

String

elementHeight

(读取和写入)

元素的高度(以页面单位计)。

Double

elementPositionX

(读取和写入)

元素的锚点位置的 x 位置。 分配或报告的单位为页面单位。

Double

elementPositionY

(读取和写入)

元素的锚点位置的 y 位置。 分配或报告的单位为页面单位。

Double

elementRotation

(读取和写入)

元素旋转角度(以度为单位)。 正值将使方向顺时针旋转,负值将使方向逆时针旋转。

Double

elementWidth

(读取和写入)

元素的宽度(以页面单位计)。

Double

fontFamilyName

(读取和写入)

与元素关联的文本符号字体。

注:

功能区上的 字体名称 下拉列表中显示的值并非始终与 font_style_name 属性一致。 可变字体包含字体样式的命名实例,并允许进行自定义。 设置值之前,您可以在功能区上进行设置,并验证返回的属性值。

String

fontStyleName

(读取和写入)

根据字体的不同,样式可能包括常规、粗体、斜体及其任意组合或扩展列表。

注:

功能区上的 字体样式 下拉列表中显示的值并非始终与 font_style_name 属性一致。 可变字体包含字体样式的命名实例,并允许进行自定义。 设置值之前,您可以在功能区上进行设置,并验证返回的属性值。

String

isOverflowing

(只读)

如果文本不在所提供几何的边界内,则返回 True 。 这种情况下,布局上通常会显示红色省略号。 您可通过它来更改字体大小或增大将容纳文本的几何。

Boolean

locked

(读取和写入)

设置为 True 时,无法在布局视图中以图形方式选择元素。

Boolean

longName

(只读)

元素的全名,包括组信息(如果存在)。 例如,在一个名称为 Text 的组元素中,名称为 Group Element 的元素将返回 longNameGroup Element\\Text 值。 如果元素不在组中,则 longNamename 值相同。

String

name

(读取和写入)

元素的名称。 有必要确保所有元素均具有唯一名称,因为这样可以轻松对其进行引用。

String

parentGroupElement

(只读)

如果元素在组中,则返回的值为 GroupElement ,否则返回 NoneType

GroupElement

text

(读取和写入)

与元素关联的文本字符串。

String

textAngle

(读取和写入)

文本字符串旋转的角度(以度为单位)。 正值将使方向顺时针旋转,负值将使方向逆时针旋转。

Double

textSize

(读取和写入)

元素文本大小(以磅为单位)。

Double

type

(只读)

返回值 TEXT_ELEMENT

String

visible

(读取和写入)

指定元素在布局或图形图层中是否可见。

Boolean

方法

applyStyleItem(style_item)

StyleItem 应用于 TextElement

名称 说明 数据类型

style_item

A reference to a StyleItem in a project.

StyleItem

clone({suffix})

提供了一种克隆页面布局中现有文本元素的机制。

名称 说明 数据类型

suffix

(可选)

用于标记每个新建文本元素的可选字符串。新元素的元素名称为父项文本元素的元素名称加上 suffix 值以及数值定序符。例如,如果父元素名称为 FieldLabelsuffix 值为 _copy ,则新克隆的元素的名称为 FieldLabel_copyFieldLabel_copy_1FieldLabel_copy_2 等。如果未提供 suffix ,则名称类似于 FieldLabel_1FieldLabel_2FieldLabel_3 等。

String

delete()

提供了一种删除页面布局中现有文本元素的机制。

getDefinition(cim_version)

返回文本元素的 CIM 定义。

名称 说明 数据类型

cim_version

A string that represents the major version of the CIM that will be used.

  • V2—The 2.x version of the CIM will be used.

  • V3—The 3.x version of the CIM will be used.

String

返回值

数据类型 说明

Object

返回 TextElement 的 CIM 定义。

setAnchor(anchor)

setAnchor 方法用于控制锚点位置。

名称 说明 数据类型

anchor

A string that specifies an anchor position.

  • BOTTOM_LEFT_CORNER—The anchor will be set at the bottom left corner position.

  • BOTTOM_MID_POINT—The anchor will be set at the bottom center position.

  • BOTTOM_RIGHT_CORNER—The anchor will be set at the bottom right corner position.

  • CENTER_POINT—The anchor will be set at the center position.

  • LEFT_MID_POINT—The anchor will be set at the left center position.

  • RIGHT_MID_POINT—The anchor will be set at the right center position.

  • TOP_LEFT_CORNER—The anchor will be set at the top left corner position.

  • TOP_MID_POINT—The anchor will be set at the top center position.

  • TOP_RIGHT_CORNER—The anchor will be set at the top right corner position.

String

setDefinition(definition_object)

设置文本元素的 CIM 定义。

名称 说明 数据类型

definition_object

A modified CIM definition object originally retrieved using getDefinition.

Object

代码示例

TextElement 示例 1

以下脚本可将工程的所有布局中包含年份的所有布局文本元素字符串中的 2022 替换为 2023。

import arcpy

search_text = '2022'
replace_text = '2023'

p = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite.aprx')
for lyt in p.listLayouts():
  for txt in lyt.listElements('TEXT_ELEMENT'):
    if search_text in txt.text:
      print(f'For element: "{txt.name}" in layout: "{lyt.name}"')
      print(f'  Replacing: "{txt.text}"')
      txt.text = txt.text.replace(search_text, replace_text)
      print(f'  With: "{txt.text}"')
  print('')

p.save()
TextElement 示例 2

以下脚本可创建一个布局,然后使用系统样式项目创建一个文本元素。 接下来,脚本将更改锚点位置,使文本的大小被调整时,其仍处于布局的中心。 最后,脚本会调整文本大小以适应布局的宽度,相对于边缘留有 10% 的缓冲距离。

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Point Text')
lyt.openView()

#Create point text element using a system style item
txtStyleItem = p.listStyleItems('ArcGIS 2D', 'TEXT', 'Title (Serif)')[0]
ptTxt = p.createTextElement(lyt, arcpy.Point(4.25, 10), 'POINT',
                            'Fit My Title To Layout Width, Less 10%',
                            10, style_item=txtStyleItem)

#Change the anchor position and reposition the text to center
ptTxt.setAnchor('Center_Point')
ptTxt.elementPositionX = 4.25
ptTxt.elementPositionY = 10

#Adjust text size to fit the width of the layout
while ptTxt.elementWidth < (lyt.pageWidth - (lyt.pageWidth * 0.1)):
  ptTxt.textSize = ptTxt.textSize + 0.1
TextElement 示例 3

以下脚本可创建一个地图,添加一个图层文件,然后创建一个图形图层。 然后,脚本会遍历图层中的每个要素,并基于要素的 name 值生成一个地图图形文本元素。

p = arcpy.mp.ArcGISProject('current')

#Create a map, add a layer file and create a graphics layer
m = p.createMap('New Map with Text Graphics', 'Map')
lyrFile = arcpy.mp.LayerFile(r'C:\Projects\GreatLakes\GreatLakes_CenterPts.lyrx')
m.addLayer(lyrFile)
lyr = m.listLayers('GreatLakes_CenterPoint')[0]
gl = m.createGraphicsLayer('New Graphics Layer')

#Create a map graphic at each point location using each feature's name value
txtStyleItem = p.listStyleItems('ArcGIS 2D', 'TEXT', 'Water (Large)')[0]
for row in arcpy.da.SearchCursor(lyr, ['SHAPE@XY', 'NAME']):
  x, y = row[0]
  txt = p.createTextElement(gl, arcpy.Point(x,y), 'POINT', row[1])

m.openView()
TextElement 示例 4

以下脚本可使用 JSON 模板创建一个曲线 (arc) 和一个贝塞尔曲线几何。 该几何用于在新布局中创建两个图形元素和两个文本元素。 可以选择性地使用 Python CIM 访问修改贝塞尔曲线的属性。 有关使用 JSON 创建几何对象的详细信息,请参阅 几何对象 开发人员帮助主题。

p = arcpy.mp.ArcGISProject('current')
lyt = p.createLayout(6, 3, 'INCH', 'New Layout with 2 curves')

#Construct a curve/arc graphic element using a default symbol
arcPath = {"curvePaths" : [[[3.5,1.25],{"c" : [[5,1.25],[4.25, 1.75]]}]]}
arc = arcpy.AsShape(arcPath, esri_json=True)
arcGra = p.createGraphicElement(lyt, arc, name='ArcPy_Arc')
arcTxt = p.createTextElement(lyt, arc, 'LINE', 'Arc-e-Text', 24, 'Comic Sans MS', name='ArcPy_ArcText')

#Construct a bezier curve graphic element using a system style item
curveStyle = p.listStyleItems('ArcGIS 2D', 'Line', 'Dashed 1 Long 1 Short')[0]
curvePath = {"curvePaths" : [[[1.25,1.25],
                              {"b" : [[3,1.5],[1.6875,2.75],[2.125,0]]}]]}
curve = arcpy.AsShape(curvePath, esri_json=True)
curveGra = p.createGraphicElement(lyt, curve, curveStyle, 'ArcPy_Curve')
curveTxt = p.createTextElement(lyt, curve, 'LINE', 'Curved text', 24, 'Comic Sans MS', name='ArcPy_CurveText')

#Optional CIM modification
curveTxt_cim = curveTxt.getDefinition('V3')
curveTxt_cim.graphic.symbol.symbol.verticalAlignment = 'Center'
curveTxt.setDefinition(curveTxt_cim)

lyt.openView()
TextElement 示例 5

以下脚本可在新布局中创建一个矩形图形和文本元素。 脚本有意使用较长的文本字符串,以便演示如何调整文本大小以适应矩形。 脚本使用一个函数创建矩形,使用 isOverflowing 属性确定几何内是否可以容纳文本。

def MakeRec_UL(ulx, uly, w, h):
    xyRecList = [[ulx, uly], [ulx+w, uly], [ulx+w,uly-h], [ulx,uly-h], [ulx,uly]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rect = arcpy.Polygon(array)
    return rect

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Rectangle Text')
lyt.openView()

#Rectangle Text
text = '''THIS TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.
  AGAIN - THIS  TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.
  AND AGAIN - THIS TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.'''
recTxt = p.createTextElement(lyt, MakeRec_UL(0.5, 10.5, 7.5, 1), 'POLYGON',
                             text, 25, 'Arial', 'Regular', name='ArcPy_RecText')

#Reduce text to fix rectangle
while recTxt.isOverflowing:
    recTxt.textSize = recTxt.textSize - 1
TextElement 示例 6

以下脚本可在新布局中创建一个自定义面图形和文本元素。 脚本有意使用较长的文本字符串,以便演示其在几何内如何换行以及使用 isOverflowing 属性演示如何调整大小以使形状可以容纳文本。 脚本还演示了如何使用 Python CIM 访问设置文本元素的背景和边界符号系统。

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Polygon Text')
lyt.openView()

#Polygon Text
polyCoords = [[0.5, 10], [4.25, 10], [4.25, 9.5], [8, 9.5], [8, 8.5], [0.5, 8.5], [0.5, 10]]
polyShp = arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in polyCoords]))
text = 'Some Text String that is really long and is <BOL>forced to wrap to other \
lines</BOL> so that we can see how it fits the polygon shape provided to the function.'
polyTxt = p.createTextElement(lyt, polyShp, 'POLYGON', text, 25,
                              'Arial', 'Regular', name='ArcPy_PolygonText')

#Reduce text to fit shape
while polyTxt.isOverflowing:
  polyTxt.textSize = polyTxt.textSize - 1

#OPTIONAL CIM modifications
polyTxt_cim = polyTxt.getDefinition('V3')

#CIM Change text color
polyTxt_cim.graphic.symbol.symbol.symbol.symbolLayers[0].color.values = [0,0,255,100]

#CIM Create a graphic frame background symbol
bgRGBColor = arcpy.cim.CreateCIMObjectFromClassName('CIMRGBColor', 'V3')
bgRGBColor.values = [225, 225, 225, 100]
bgSolidFillLyr = arcpy.cim.CreateCIMObjectFromClassName('CIMSolidFill', 'V3')
bgSolidFillLyr.color = bgRGBColor
bgPolySym = arcpy.cim.CreateCIMObjectFromClassName('CIMPolygonSymbol', 'V3')
bgPolySym.symbolLayers = [bgSolidFillLyr]
bgSymRef = arcpy.cim.CreateCIMObjectFromClassName('CIMSymbolReference', 'V3')
bgSymRef.symbol = bgPolySym
GraphicFrame = arcpy.cim.CreateCIMObjectFromClassName('CIMGraphicFrame', 'V3')
GraphicFrame.backgroundSymbol = bgSymRef

#CIM Create a graphic frame border symbol
brdRGBColor = arcpy.cim.CreateCIMObjectFromClassName('CIMRGBColor', 'V3')
brdRGBColor.values = [255, 0, 0, 100]
brdSolidStrokeLyr = arcpy.cim.CreateCIMObjectFromClassName('CIMSolidStroke', 'V3')
brdSolidStrokeLyr.color = brdRGBColor
brdSolidStrokeLyr.miterLimit = 10
brdSolidStrokeLyr.width = 5
brdLineSym = arcpy.cim.CreateCIMObjectFromClassName('CIMLineSymbol', 'V3')
brdLineSym.symbolLayers = [brdSolidStrokeLyr]
brdSymRef = arcpy.cim.CreateCIMObjectFromClassName('CIMSymbolReference', 'V3')
brdSymRef.symbol = brdLineSym
GraphicFrame.borderSymbol = brdSymRef

polyTxt_cim.graphic.frame = GraphicFrame
polyTxt.setDefinition(polyTxt_cim)
TextElement 示例 7

以下脚本可以基于地图中某个表的数据值构建图形表。 使用名为 vertLine 的垂直线、名为 horzLine 的水平线和名为 cellText 的文本元素制作布局。 每个元素使用相应的符号系统和文本属性进行创作。 元素锚点设置为左上角位置,文本元素的垂直和水平对齐设置为左上角对齐。

def MakeRec_LL(llx, lly, w, h):
    xyRecList = [[llx, lly], [llx, lly+h], [llx+w,lly+h], [llx+w,lly], [llx,lly]]
    xyRecList = [[1,1],[1, 2], [2.75, 2], [2.75, 1], [1, 1]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rec = arcpy.Polygon(array)
    return rec

p = arcpy.mp.ArcGISProject('CURRENT')

#Create a layout
lyt = p.createLayout(6, 3, 'INCH', 'New Layout with Rectangles')

#Construct a pre-defined rectangle graphic element using a system style item
# and a rectangle function that takes x/y min/max and a width/height
# using the lower left corner as a start location

polyStyle = p.listStyleItems('ArcGIS 2D', 'Polygon', 'Orchard')[0]

p.createPredefinedGraphicElement(lyt, MakeRec_LL(1, 1, 1.75, 1), 'RECTANGLE',
                                 polyStyle, 'ArcPy_Rectangle_Env',
                                 lock_aspect_ratio=False)

#Construct the same element above using a point location
rec = p.createPredefinedGraphicElement(lyt, arcpy.Point(3, 1), 'RECTANGLE',
                                       polyStyle, 'ArcPy_Rectangle_Pt',
                                       lock_aspect_ratio=False)
rec.elementWidth = 1.75
rec.elementHeight = 1

lyt.openView()