Class Image
Image is a textured element in the UI hierarchy.
Inheritance
Implements
Inherited Members
Namespace: UnityEngine.UI
Assembly: UnityEngine.UI.dll
Syntax
[RequireComponent(typeof(CanvasRenderer))]
[AddComponentMenu("UI/Image", 11)]
public class Image : MaskableGraphic, ICanvasElement, IClippable, IMaskable, IMaterialModifier, ISerializationCallbackReceiver, ILayoutElement, ICanvasRaycastFilter
Constructors
Image()
Declaration
protected Image()
Fields
s_ETC1DefaultUI
Declaration
protected static Material s_ETC1DefaultUI
Field Value
Type | Description |
---|---|
Material |
Properties
alphaHitTestMinimumThreshold
The alpha threshold specifies the minimum alpha a pixel must have for the event to considered a "hit" on the Image.
Declaration
public float alphaHitTestMinimumThreshold { get; set; }
Property Value
Type | Description |
---|---|
float |
Remarks
Alpha values less than the threshold will cause raycast events to pass through the Image. An value of 1 would cause only fully opaque pixels to register raycast events on the Image. The alpha tested is retrieved from the image sprite only, while the alpha of the Image [[UI.Graphic.color]] is disregarded.
alphaHitTestMinimumThreshold defaults to 0; all raycast events inside the Image rectangle are considered a hit. In order for greater than 0 to values to work, the sprite used by the Image must have readable pixels. This can be achieved by enabling Read/Write enabled in the advanced Texture Import Settings for the sprite and disabling atlassing for the sprite.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class ExampleClass : MonoBehaviour
{
public Image theButton;
// Use this for initialization
void Start()
{
theButton.alphaHitTestMinimumThreshold = 0.5f;
}
}
defaultETC1GraphicMaterial
Cache of the default Canvas Ericsson Texture Compression 1 (ETC1) and alpha Material.
Declaration
public static Material defaultETC1GraphicMaterial { get; }
Property Value
Type | Description |
---|---|
Material |
Remarks
Stores the ETC1 supported Canvas Material that is returned from GetETC1SupportedCanvasMaterial(). Note: Always specify the UI/DefaultETC1 Shader in the Always Included Shader list, to use the ETC1 and alpha Material.
eventAlphaThreshold
Declaration
[Obsolete("eventAlphaThreshold has been deprecated. Use eventMinimumAlphaThreshold instead (UnityUpgradable) -> alphaHitTestMinimumThreshold")]
public float eventAlphaThreshold { get; set; }
Property Value
Type | Description |
---|---|
float |
fillAmount
Amount of the Image shown when the Image.type is set to Image.Type.Filled.
Declaration
public float fillAmount { get; set; }
Property Value
Type | Description |
---|---|
float |
Remarks
0-1 range with 0 being nothing shown, and 1 being the full Image.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Cooldown : MonoBehaviour
{
public Image cooldown;
public bool coolingDown;
public float waitTime = 30.0f;
// Update is called once per frame
void Update()
{
if (coolingDown == true)
{
//Reduce fill amount over 30 seconds
cooldown.fillAmount -= 1.0f / waitTime * Time.deltaTime;
}
}
}
fillCenter
Whether or not to render the center of a Tiled or Sliced image.
Declaration
public bool fillCenter { get; set; }
Property Value
Type | Description |
---|---|
bool |
Remarks
This will only have any effect if the Image.sprite has borders.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class FillCenterScript : MonoBehaviour
{
public Image xmasCalenderDoor;
// removes the center of the image to reveal the image behind it
void OpenCalendarDoor()
{
xmasCalenderDoor.fillCenter = false;
}
}
fillClockwise
Whether the Image should be filled clockwise (true) or counter-clockwise (false).
Declaration
public bool fillClockwise { get; set; }
Property Value
Type | Description |
---|---|
bool |
Remarks
This will only have any effect if the Image.type is set to Image.Type.Filled and Image.fillMethod is set to any of the Radial methods.
Examples
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class FillClockwiseScript : MonoBehaviour
{
public Image healthCircle;
// This method sets the direction of the health circle.
// Clockwise for the Player, Counter Clockwise for the opponent.
void SetHealthDirection(GameObject target)
{
if (target.tag == "Player")
{
healthCircle.fillClockwise = true;
}
else if (target.tag == "Opponent")
{
healthCircle.fillClockwise = false;
}
}
}
fillMethod
Declaration
public Image.FillMethod fillMethod { get; set; }
Property Value
Type | Description |
---|---|
Image.FillMethod |
fillOrigin
Controls the origin point of the Fill process. Value means different things with each fill method.
Declaration
public int fillOrigin { get; set; }
Property Value
Type | Description |
---|---|
int |
Remarks
You should cast to the appropriate origin type: Image.OriginHorizontal, Image.OriginVertical, Image.Origin90, Image.Origin180 or Image.Origin360 depending on the Image.Fillmethod. Note: This will only have any effect if the Image.type is set to Image.Type.Filled.
Examples
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
[RequireComponent(typeof(Image))]
public class ImageOriginCycle : MonoBehaviour
{
void OnEnable()
{
Image image = GetComponent<Image>();
string fillOriginName = "";
switch ((Image.FillMethod)image.fillMethod)
{
case Image.FillMethod.Horizontal:
fillOriginName = ((Image.OriginHorizontal)image.fillOrigin).ToString();
break;
case Image.FillMethod.Vertical:
fillOriginName = ((Image.OriginVertical)image.fillOrigin).ToString();
break;
case Image.FillMethod.Radial90:
fillOriginName = ((Image.Origin90)image.fillOrigin).ToString();
break;
case Image.FillMethod.Radial180:
fillOriginName = ((Image.Origin180)image.fillOrigin).ToString();
break;
case Image.FillMethod.Radial360:
fillOriginName = ((Image.Origin360)image.fillOrigin).ToString();
break;
}
Debug.Log(string.Format("{0} is using {1} fill method with the origin on {2}", name, image.fillMethod, fillOriginName));
}
}
flexibleHeight
See ILayoutElement.flexibleHeight.
Declaration
public virtual float flexibleHeight { get; }
Property Value
Type | Description |
---|---|
float |
flexibleWidth
See ILayoutElement.flexibleWidth.
Declaration
public virtual float flexibleWidth { get; }
Property Value
Type | Description |
---|---|
float |
hasBorder
Whether the Sprite of the image has a border to work with.
Declaration
public bool hasBorder { get; }
Property Value
Type | Description |
---|---|
bool |
layoutPriority
See ILayoutElement.layoutPriority.
Declaration
public virtual int layoutPriority { get; }
Property Value
Type | Description |
---|---|
int |
mainTexture
Image's texture comes from the UnityEngine.Image.
Declaration
public override Texture mainTexture { get; }
Property Value
Type | Description |
---|---|
Texture |
Overrides
material
The specified Material used by this Image. The default Material is used instead if one wasn't specified.
Declaration
public override Material material { get; set; }
Property Value
Type | Description |
---|---|
Material |
Overrides
minHeight
See ILayoutElement.minHeight.
Declaration
public virtual float minHeight { get; }
Property Value
Type | Description |
---|---|
float |
minWidth
See ILayoutElement.minWidth.
Declaration
public virtual float minWidth { get; }
Property Value
Type | Description |
---|---|
float |
multipliedPixelsPerUnit
Declaration
protected float multipliedPixelsPerUnit { get; }
Property Value
Type | Description |
---|---|
float |
overrideSprite
Set an override sprite to be used for rendering.
Declaration
public Sprite overrideSprite { get; set; }
Property Value
Type | Description |
---|---|
Sprite |
Remarks
The UI.Image-overrideSprite|overrideSprite variable allows a sprite to have the sprite changed.This change happens immediately.When the changed sprite is no longer needed the sprite can be reverted back to the original version.This happens when the overrideSprite is set to /null/.
Examples
Note: The script example below has two buttons. The button textures are loaded from the /Resources/ folder. (They are not used in the shown example). Two sprites are added to the example code. /Example1/ and /Example2/ are functions called by the button OnClick functions. Example1 calls overrideSprite and Example2 sets overrideSprite to null.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ExampleClass : MonoBehaviour
{
private Sprite sprite1;
private Sprite sprite2;
private Image i;
public void Start()
{
i = GetComponent<Image>();
sprite1 = Resources.Load<Sprite>("texture1");
sprite2 = Resources.Load<Sprite>("texture2");
i.sprite = sprite1;
}
// Called by a Button OnClick() with ExampleClass.Example1
// Uses overrideSprite to make this change temporary
public void Example1()
{
i.overrideSprite = sprite2;
}
// Called by a Button OnClick() with ExampleClass.Example2
// Removes the overrideSprite which causes the original sprite to be used again.
public void Example2()
{
i.overrideSprite = null;
}
}
pixelsPerUnit
Declaration
public float pixelsPerUnit { get; }
Property Value
Type | Description |
---|---|
float |
pixelsPerUnitMultiplier
Pixel per unit modifier to change how sliced sprites are generated.
Declaration
public float pixelsPerUnitMultiplier { get; set; }
Property Value
Type | Description |
---|---|
float |
preferredHeight
If there is a sprite being rendered returns the size of that sprite. In the case of a slided or tiled sprite will return the calculated minimum size possible
Declaration
public virtual float preferredHeight { get; }
Property Value
Type | Description |
---|---|
float |
preferredWidth
If there is a sprite being rendered returns the size of that sprite. In the case of a slided or tiled sprite will return the calculated minimum size possible
Declaration
public virtual float preferredWidth { get; }
Property Value
Type | Description |
---|---|
float |
preserveAspect
Whether this image should preserve its Sprite aspect ratio.
Declaration
public bool preserveAspect { get; set; }
Property Value
Type | Description |
---|---|
bool |
sprite
The sprite that is used to render this image.
Declaration
public Sprite sprite { get; set; }
Property Value
Type | Description |
---|---|
Sprite |
Remarks
This returns the source Sprite of an Image. This Sprite can also be viewed and changed in the Inspector as part of an Image component. This can also be used to change the Sprite using a script.
Examples
//Attach this script to an Image GameObject and set its Source Image to the Sprite you would like.
//Press the space key to change the Sprite. Remember to assign a second Sprite in this script's section of the Inspector.
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
Image m_Image;
//Set this in the Inspector
public Sprite m_Sprite;
void Start()
{
//Fetch the Image from the GameObject
m_Image = GetComponent<Image>();
}
void Update()
{
//Press space to change the Sprite of the Image
if (Input.GetKey(KeyCode.Space))
{
m_Image.sprite = m_Sprite;
}
}
}
type
How to display the image.
Declaration
public Image.Type type { get; set; }
Property Value
Type | Description |
---|---|
Image.Type |
Remarks
Unity can interpret an Image in various different ways depending on the intended purpose. This can be used to display:
- Whole images stretched to fit the RectTransform of the Image.
- A 9-sliced image useful for various decorated UI boxes and other rectangular elements.
- A tiled image with sections of the sprite repeated.
- As a partial image, useful for wipes, fades, timers, status bars etc.
useSpriteMesh
Allows you to specify whether the UI Image should be displayed using the mesh generated by the TextureImporter, or by a simple quad mesh.
Declaration
public bool useSpriteMesh { get; set; }
Property Value
Type | Description |
---|---|
bool |
Remarks
When this property is set to false, the UI Image uses a simple quad. When set to true, the UI Image uses the sprite mesh generated by the [[TextureImporter]]. You should set this to true if you want to use a tightly fitted sprite mesh based on the alpha values in your image. Note: If the texture importer's SpriteMeshType property is set to SpriteMeshType.FullRect, it will only generate a quad, and not a tightly fitted sprite mesh, which means this UI image will be drawn using a quad regardless of the value of this property. Therefore, when enabling this property to use a tightly fitted sprite mesh, you must also ensure the texture importer's SpriteMeshType property is set to Tight.
Methods
CalculateLayoutInputHorizontal()
See ILayoutElement.CalculateLayoutInputHorizontal.
Declaration
public virtual void CalculateLayoutInputHorizontal()
CalculateLayoutInputVertical()
See ILayoutElement.CalculateLayoutInputVertical.
Declaration
public virtual void CalculateLayoutInputVertical()
DisableSpriteOptimizations()
Disable all automatic sprite optimizations.
Declaration
public void DisableSpriteOptimizations()
Remarks
When a new Sprite is assigned update optimizations are automatically applied.
IsRaycastLocationValid(Vector2, Camera)
Calculate if the ray location for this image is a valid hit location. Takes into account a Alpha test threshold.
Declaration
public virtual bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
Parameters
Type | Name | Description |
---|---|---|
Vector2 | screenPoint | The screen point to check against |
Camera | eventCamera | The camera in which to use to calculate the coordinating position |
Returns
Type | Description |
---|---|
bool | If the location is a valid hit or not. |
Remarks
Also see See:ICanvasRaycastFilter.
OnAfterDeserialize()
See ISerializationCallbackReceiver.
Declaration
public virtual void OnAfterDeserialize()
OnBeforeSerialize()
See ISerializationCallbackReceiver.
Declaration
public virtual void OnBeforeSerialize()
OnCanvasHierarchyChanged()
Called when the state of the parent Canvas is changed.
Declaration
protected override void OnCanvasHierarchyChanged()
Overrides
OnDidApplyAnimationProperties()
Declaration
protected override void OnDidApplyAnimationProperties()
Overrides
OnDisable()
Clear references.
Declaration
protected override void OnDisable()
Overrides
OnEnable()
Mark the Graphic and the canvas as having been changed.
Declaration
protected override void OnEnable()
Overrides
OnPopulateMesh(VertexHelper)
Update the UI renderer mesh.
Declaration
protected override void OnPopulateMesh(VertexHelper toFill)
Parameters
Type | Name | Description |
---|---|---|
VertexHelper | toFill |
Overrides
OnValidate()
Declaration
protected override void OnValidate()
Overrides
SetNativeSize()
Adjusts the image size to make it pixel-perfect.
Declaration
public override void SetNativeSize()
Overrides
Remarks
This means setting the Images RectTransform.sizeDelta to be equal to the Sprite dimensions.
UpdateMaterial()
Update the renderer's material.
Declaration
protected override void UpdateMaterial()