CanvasItem¶
Clase base de cualquier cosa 2D.
Descripción¶
Clase base de cualquier cosa 2D. Los objetos de Canvas se colocan en un árbol; los niños heredan y extienden la la transformada de su padre. CanvasItem
se extiende por Control para cualquier cosa relacionada con la GUI, y por Node2D para cualquier cosa relacionada con el motor 2D.
Cualquier CanvasItem
puede dibujar. Para ello, se debe llamar a update, luego se recibirá NOTIFICATION_DRAW en tiempo de inactividad para solicitar el redibujo. Debido a esto, los elementos de canvas no necesitan ser redibujados en cada cuadro, mejorando el rendimiento significativamente. Se proporcionan varias funciones para dibujar en el CanvasItem
(ver las funciones draw_*
). Sin embargo, sólo pueden utilizarse dentro de las funciones virtuales Object._notification, de señal o _draw.
Los elementos de Canvas se dibujan en orden del árbol. Por defecto, los niños están encima de sus padres, por lo que una raíz CanvasItem
se dibujará detrás de todo. Este comportamiento puede ser cambiado por cada elemento.
Un CanvasItem
también puede ser escondido, lo que también esconderá a sus hijos. Proporciona muchas maneras de cambiar parámetros como la modulación (para sí mismo y sus hijos) y la auto-modulación (sólo para sí mismo), así como su modo de mezcla.
En última instancia, se puede solicitar una notificación de transformación, que notificará al nodo que su posición global ha cambiado en caso de que el árbol padre haya cambiado.
Nota: A menos que se especifique lo contrario, todos los métodos que tienen parámetros de ángulo deben tener ángulos especificados como radianes. Para convertir los grados a radianes, use @GDScript.deg2rad.
Tutoriales¶
Propiedades¶
|
||
|
||
|
||
|
||
|
||
|
Métodos¶
void |
_draw ( ) virtual |
void |
draw_arc ( Vector2 center, float radius, float start_angle, float end_angle, int point_count, Color color, float width=1.0, bool antialiased=false ) |
draw_char ( Font font, Vector2 position, String char, String next, Color modulate=Color( 1, 1, 1, 1 ) ) |
|
void |
draw_circle ( Vector2 position, float radius, Color color ) |
void |
draw_colored_polygon ( PoolVector2Array points, Color color, PoolVector2Array uvs=PoolVector2Array( ), Texture texture=null, Texture normal_map=null, bool antialiased=false ) |
void |
draw_line ( Vector2 from, Vector2 to, Color color, float width=1.0, bool antialiased=false ) |
void |
draw_mesh ( Mesh mesh, Texture texture, Texture normal_map=null, Transform2D transform=Transform2D( 1, 0, 0, 1, 0, 0 ), Color modulate=Color( 1, 1, 1, 1 ) ) |
void |
draw_multiline ( PoolVector2Array points, Color color, float width=1.0, bool antialiased=false ) |
void |
draw_multiline_colors ( PoolVector2Array points, PoolColorArray colors, float width=1.0, bool antialiased=false ) |
void |
draw_multimesh ( MultiMesh multimesh, Texture texture, Texture normal_map=null ) |
void |
draw_polygon ( PoolVector2Array points, PoolColorArray colors, PoolVector2Array uvs=PoolVector2Array( ), Texture texture=null, Texture normal_map=null, bool antialiased=false ) |
void |
draw_polyline ( PoolVector2Array points, Color color, float width=1.0, bool antialiased=false ) |
void |
draw_polyline_colors ( PoolVector2Array points, PoolColorArray colors, float width=1.0, bool antialiased=false ) |
void |
draw_primitive ( PoolVector2Array points, PoolColorArray colors, PoolVector2Array uvs, Texture texture=null, float width=1.0, Texture normal_map=null ) |
void |
draw_rect ( Rect2 rect, Color color, bool filled=true, float width=1.0, bool antialiased=false ) |
void |
draw_set_transform ( Vector2 position, float rotation, Vector2 scale ) |
void |
draw_set_transform_matrix ( Transform2D xform ) |
void |
draw_string ( Font font, Vector2 position, String text, Color modulate=Color( 1, 1, 1, 1 ), int clip_w=-1 ) |
void |
draw_style_box ( StyleBox style_box, Rect2 rect ) |
void |
draw_texture ( Texture texture, Vector2 position, Color modulate=Color( 1, 1, 1, 1 ), Texture normal_map=null ) |
void |
draw_texture_rect ( Texture texture, Rect2 rect, bool tile, Color modulate=Color( 1, 1, 1, 1 ), bool transpose=false, Texture normal_map=null ) |
void |
draw_texture_rect_region ( Texture texture, Rect2 rect, Rect2 src_rect, Color modulate=Color( 1, 1, 1, 1 ), bool transpose=false, Texture normal_map=null, bool clip_uv=true ) |
void |
|
get_canvas ( ) const |
|
get_canvas_item ( ) const |
|
get_canvas_transform ( ) const |
|
get_global_mouse_position ( ) const |
|
get_global_transform ( ) const |
|
get_global_transform_with_canvas ( ) const |
|
get_local_mouse_position ( ) const |
|
get_transform ( ) const |
|
get_viewport_rect ( ) const |
|
get_viewport_transform ( ) const |
|
get_world_2d ( ) const |
|
void |
hide ( ) |
is_local_transform_notification_enabled ( ) const |
|
is_set_as_toplevel ( ) const |
|
is_transform_notification_enabled ( ) const |
|
is_visible_in_tree ( ) const |
|
make_canvas_position_local ( Vector2 screen_point ) const |
|
make_input_local ( InputEvent event ) const |
|
void |
set_as_toplevel ( bool enable ) |
void |
set_notify_local_transform ( bool enable ) |
void |
set_notify_transform ( bool enable ) |
void |
show ( ) |
void |
update ( ) |
Señales¶
draw ( )
Emitido cuando el CanvasItem
debe ser dibujado de nuevo. Esto sólo puede ser conectado en tiempo real, ya que en diferido no se podrá dibujar.
hide ( )
Emitido al ocultarse.
item_rect_changed ( )
Emitted when the item's Rect2 boundaries (position or size) have changed, or when an action is taking place that may have impacted these boundaries (e.g. changing Sprite.texture).
visibility_changed ( )
Emitido cuando la visibilidad (oculta/visible) cambia.
Enumeraciones¶
enum BlendMode:
BLEND_MODE_MIX = 0 --- Modo de mezcla. Se supone que los colores son independientes del valor alfa (opacidad).
BLEND_MODE_ADD = 1 --- Modo de mezcla de añadidos.
BLEND_MODE_SUB = 2 --- Modo de mezcla de substracción.
BLEND_MODE_MUL = 3 --- Modo de mezcla multiplicativo.
BLEND_MODE_PREMULT_ALPHA = 4 --- Modo de mezcla Mix. Se supone que los colores se premultiplican por el valor alfa (opacidad).
BLEND_MODE_DISABLED = 5 --- Disables blending mode. Colors including alpha are written as-is. Only applicable for render targets with a transparent background. No lighting will be applied.
Constantes¶
NOTIFICATION_TRANSFORM_CHANGED = 2000 --- La transformada del
CanvasItem
ha cambiado. Esta notificación sólo se recibe si está habilitada por set_notify_transform o set_notify_local_transform.NOTIFICATION_DRAW = 30 --- Se solicita al
CanvasItem
que dibuje.NOTIFICATION_VISIBILITY_CHANGED = 31 --- La visibilidad del
CanvasItem
ha cambiado.NOTIFICATION_ENTER_CANVAS = 32 --- El
CanvasItem
ha entrado en el canvas.NOTIFICATION_EXIT_CANVAS = 33 --- El
CanvasItem
ha salido del canvas.
Descripciones de Propiedades¶
int light_mask
Default |
|
Setter |
set_light_mask(value) |
Getter |
get_light_mask() |
Las capas de renderización en las que este CanvasItem
responde a los nodos Light2D.
Material material
Setter |
set_material(value) |
Getter |
get_material() |
El material aplicado a las texturas en este CanvasItem
.
Color modulate
Default |
|
Setter |
set_modulate(value) |
Getter |
get_modulate() |
El color aplicado a las texturas en este CanvasItem
.
Color self_modulate
Default |
|
Setter |
set_self_modulate(value) |
Getter |
get_self_modulate() |
El color aplicado a las texturas en este CanvasItem
. Esto no es heredado por los hijos de CanvasItem
.
bool show_behind_parent
Default |
|
Setter |
set_draw_behind_parent(value) |
Getter |
is_draw_behind_parent_enabled() |
Si true
, el objeto se dibuja detrás de su padre.
bool show_on_top
Si true
, el objeto se dibuja encima de su padre.
bool use_parent_material
Default |
|
Setter |
set_use_parent_material(value) |
Getter |
get_use_parent_material() |
Si true
, la propiedad del material de CanvasItem
se utiliza como el material para este elemento.
bool visible
Default |
|
Setter |
set_visible(value) |
Getter |
is_visible() |
Si true
, se dibuja este CanvasItem
. El nodo sólo es visible si todos sus antecedentes también lo son (en otras palabras, is_visible_in_tree debe devolver true
).
Nota: Para los controles que heredan Popup, la forma correcta de hacerlos visibles es llamar a una de las múltiples funciones popup*()
en su lugar.
Descripciones de Métodos¶
void _draw ( ) virtual
Función sobreescribible llamada por el motor (si está definida) para dibujar el objeto canvas.
void draw_arc ( Vector2 center, float radius, float start_angle, float end_angle, int point_count, Color color, float width=1.0, bool antialiased=false )
Dibuja un arco entre los ángulos dados. Cuanto mayor sea el valor de point_count
, más suave será la curva.
float draw_char ( Font font, Vector2 position, String char, String next, Color modulate=Color( 1, 1, 1, 1 ) )
Dibuja un carácter de cadena usando una fuente personalizada. Devuelve el avance, dependiendo del ancho del carácter y del kerning con un opcional siguiente carácter.
Dibuja un círculo de color.
void draw_colored_polygon ( PoolVector2Array points, Color color, PoolVector2Array uvs=PoolVector2Array( ), Texture texture=null, Texture normal_map=null, bool antialiased=false )
Dibuja un polígono coloreado de cualquier cantidad de puntos, convexo o cóncavo.
Draws a line from a 2D point to another, with a given color and width. It can be optionally antialiased.
void draw_mesh ( Mesh mesh, Texture texture, Texture normal_map=null, Transform2D transform=Transform2D( 1, 0, 0, 1, 0, 0 ), Color modulate=Color( 1, 1, 1, 1 ) )
Dibuja una Mesh en 2D, usando la textura proporcionada. Ver MeshInstance2D para la documentación relacionada.
void draw_multiline ( PoolVector2Array points, Color color, float width=1.0, bool antialiased=false )
Draws multiple, parallel lines with a uniform color
.
Note: width
and antialiased
are currently not implemented and have no effect.
void draw_multiline_colors ( PoolVector2Array points, PoolColorArray colors, float width=1.0, bool antialiased=false )
Draws multiple, parallel lines with a uniform width
and segment-by-segment coloring. Colors assigned to line segments match by index between points
and colors
.
Note: width
and antialiased
are currently not implemented and have no effect.
Dibuja una MultiMesh en 2D con la textura proporcionada. Ver MultiMeshInstance2D para la documentación relacionada.
void draw_polygon ( PoolVector2Array points, PoolColorArray colors, PoolVector2Array uvs=PoolVector2Array( ), Texture texture=null, Texture normal_map=null, bool antialiased=false )
Dibuja un polígono de cualquier cantidad de puntos, convexo o cóncavo.
void draw_polyline ( PoolVector2Array points, Color color, float width=1.0, bool antialiased=false )
Draws interconnected line segments with a uniform color
and width
and optional antialiasing.
void draw_polyline_colors ( PoolVector2Array points, PoolColorArray colors, float width=1.0, bool antialiased=false )
Draws interconnected line segments with a uniform width
, segment-by-segment coloring, and optional antialiasing. Colors assigned to line segments match by index between points
and colors
.
void draw_primitive ( PoolVector2Array points, PoolColorArray colors, PoolVector2Array uvs, Texture texture=null, float width=1.0, Texture normal_map=null )
Draws a custom primitive. 1 point for a point, 2 points for a line, 3 points for a triangle and 4 points for a quad.
void draw_rect ( Rect2 rect, Color color, bool filled=true, float width=1.0, bool antialiased=false )
Draws a rectangle. If filled
is true
, the rectangle will be filled with the color
specified. If filled
is false
, the rectangle will be drawn as a stroke with the color
and width
specified. If antialiased
is true
, the lines will be antialiased.
Note: width
and antialiased
are only effective if filled
is false
.
Establece una transformación personalizada para el dibujo a través de los componentes. Todo lo que se dibuje después será transformado por esto.
void draw_set_transform_matrix ( Transform2D xform )
Establece una transformación personalizada para dibujar a través de la matriz. Todo lo que se dibuje después será transformado por esto.
void draw_string ( Font font, Vector2 position, String text, Color modulate=Color( 1, 1, 1, 1 ), int clip_w=-1 )
Draws text
using the specified font
at the position
(bottom-left corner using the baseline of the font). The text will have its color multiplied by modulate
. If clip_w
is greater than or equal to 0, the text will be clipped if it exceeds the specified width.
Example using the default project font:
# If using this method in a script that redraws constantly, move the
# `default_font` declaration to a member variable assigned in `_ready()`
# so the Control is only created once.
var default_font = Control.new().get_font("font")
draw_string(default_font, Vector2(64, 64), "Hello world")
See also Font.draw.
Dibuja un rectángulo con estilo.
void draw_texture ( Texture texture, Vector2 position, Color modulate=Color( 1, 1, 1, 1 ), Texture normal_map=null )
Dibuja una textura en una posición determinada.
void draw_texture_rect ( Texture texture, Rect2 rect, bool tile, Color modulate=Color( 1, 1, 1, 1 ), bool transpose=false, Texture normal_map=null )
Dibuja un rectángulo con textura en una posición determinada, opcionalmente modulada por un color. Si transpose
es true
, la textura tendrá sus coordenadas X e Y intercambiadas.
void draw_texture_rect_region ( Texture texture, Rect2 rect, Rect2 src_rect, Color modulate=Color( 1, 1, 1, 1 ), bool transpose=false, Texture normal_map=null, bool clip_uv=true )
Dibuja una región de rectángulo con textura en una posición determinada, opcionalmente modulada por un color. Si transpose
es true
, la textura tendrá sus coordenadas X e Y intercambiadas.
void force_update_transform ( )
Obliga a la transformación a actualizarse. Los cambios en la física de las transformaciones no son instantáneos por razones de rendimiento. Las transformaciones se acumulan y luego se fijan. Usa esto si necesitas una transformación actualizada cuando hagas operaciones de física.
RID get_canvas ( ) const
Devuelve el RID del canvas World2D donde el objeto esta contenido.
RID get_canvas_item ( ) const
Returns the canvas item RID used by VisualServer for this item.
Transform2D get_canvas_transform ( ) const
Devuelve la matriz de transformación de este objeto canvas.
Vector2 get_global_mouse_position ( ) const
Devuelve la posición global del ratón.
Transform2D get_global_transform ( ) const
Devuelve la matriz de transformación global de este objeto.
Transform2D get_global_transform_with_canvas ( ) const
Devuelve la matriz de transformación global de este objeto en relación con el canvas.
Vector2 get_local_mouse_position ( ) const
Devuelve la posición del ratón relativa a la posición de este objeto.
Transform2D get_transform ( ) const
Devuelve la matriz de transformación de este objecto.
Rect2 get_viewport_rect ( ) const
Devuelve los límites del viewport como un Rect2.Devuelve los límites del viewport como un Rect2.
Transform2D get_viewport_transform ( ) const
Devuelve la transformación de este objeto en relación con el viewport.
World2D get_world_2d ( ) const
Devuelve el World2D donde está este objeto.
void hide ( )
Ocultar el CanvasItem
si es visible actualmente.
bool is_local_transform_notification_enabled ( ) const
Devuelve true
si se comunican notificaciones de transformación local a los hijos.
bool is_set_as_toplevel ( ) const
Devuelve true
si el nodo está configurado como de nivel superior. Ver set_as_toplevel.
bool is_transform_notification_enabled ( ) const
Devuelve true
si las notificaciones de transformación global se comunican a los hijos.
bool is_visible_in_tree ( ) const
Devuelve true
si el nodo está presente en el SceneTree, su propiedad visible es true
y todos sus antecedentes también son visibles. Si algún antecedente está oculto, este nodo no será visible en el árbol de la escena.
Asigna screen_point
como la nueva transformación local de este nodo.
InputEvent make_input_local ( InputEvent event ) const
Las transformaciones emitidas por los event
s de entrada se aplican en el espacio local en lugar del espacio global.
void set_as_toplevel ( bool enable )
Si enable
es true
, el nodo no heredará su transformación de los objetos del canvas padre.
void set_notify_local_transform ( bool enable )
Si enable
es true
, los hijos serán actualizados con datos de transformación local.
void set_notify_transform ( bool enable )
Si enable
es true
, los hijos serán actualizados con los datos de transformación global.
void show ( )
Muestra el CanvasItem
si está actualmente oculto. Para los controles que heredan Popup, la forma correcta de hacerlos visibles es llamar a una de las múltiples funciones popup*()
en su lugar.
void update ( )
Pone en la cola el CanvasItem
para la actualización. La NOTIFICATION_DRAW será llamada en tiempo de inactividad para solicitar el redibujado.