Main Content

Viewer Properties

R2026b

Viewer for 2-D and 3-D image display

Renamed from Viewer3D in R2024b

Viewer properties control the appearance and behavior of a Viewer object. By changing property values, you can manage scene-level controls for 2-D and 3-D image display. Create a Viewer object configured for 2-D image display using the using the viewer2d function. Create a Viewer object configured for 3-D image display using the viewer3d function.

Use dot notation to query and set properties. For example, these commands show how to create a Viewer object, query the value of the BackgroundColor property, and set the value of the BackgroundColor property, respectively.

viewer = viewer3d;
c = viewer.BackgroundColor;
viewer.BackgroundColor = "blue";

Camera Controls

expand all

Camera position, or viewpoint, specified as a 3-element vector of the form [x y z]. The camera is oriented along the view axis, which is a straight line that connects the camera position and the camera target. Changing the CameraPosition property changes the point from which you view the image or volume. For an illustration, see Camera Graphics Terminology.

Camera target, specified as a 3-element vector of the form [x y z]. The camera is oriented along the view axis, which is a straight line that connects the camera position and the camera target. For an illustration, see Camera Graphics Terminology.

Upwards direction for the camera, specified as a 3-element vector of the form [x y z]. By default, the z-axis is the up direction ([0 0 1]). For an illustration, see Camera Graphics Terminology.

Camera zoom level, specified as a positive number.

Since R2026a

Style of the camera projection onto a 2-D screen, specified as "orthographic" or "perspective".

ValueDescription
"orthographic"Maintain the correct relative dimensions of graphics objects regarding the distance of a given point from the viewer, and draw lines that are parallel in the data parallel on the screen.
"perspective"Incorporate foreshortening, which enables you to perceive depth in 2-D representations of 3-D objects. Perspective projection does not preserve the relative dimensions of objects. Instead, it displays a distant object smaller than a nearer object of the same length. Lines that are parallel in the data might not appear parallel on screen. The ScaleBar property is not supported for the perspective camera view.

Since R2026a

Behavior of the rotation, zoom, and pan camera interactions, specified as one of the options in the table.

StyleDescriptionZoomPanRotateSupported Camera Projection
"scene-orbit"

Default value for 3-D viewers created using viewer3d or volshow.

This value is suitable for most basic volume displays.

Scroll to zoom in to the location of the pointer.Click and drag to move the camera side to side or up and down.Rotate the camera around the scene center.Both
"click-orbit"This value is commonly used for point cloud displays.Scroll to zoom in to the location of the pointer.

Click and drag to move the camera side to side or up and down.

Rotate the camera around the clicked location.Both
"target-orbit"This value is useful when you want to focus on a specific location or object in a scene. You can programmatically set the location to focus on by using the CameraTarget property.

Scroll to zoom in to the camera target.

Click and drag to move the camera side to side or up and down.

Rotate the camera around the camera target.Both
"focus-orbit"This value is useful when you want to zoom in to a particular object and then rotate around it, focusing on that object.Scroll to zoom in to the surface point beneath the pointer.

Click and drag to move the camera side to side or up and down.

Rotate the camera around the most recent zoom location.Both
"planar"

Default value for 2-D viewers created using viewer2d or imageshow.

This value is suitable for 2-D image displays, or when you want to keep the plane facing the camera constant as you rotate.

Scroll to zoom in to the location of the pointer.

Click and drag to move the camera side to side or up and down.

Rotating simulates a camera roll about the scene center, such that the plane the camera faces never changes.Both
"dolly"This value is useful for simulating a first-person perspective while navigating through the scene. It is commonly used for point cloud displays.Scroll the to move camera toward or away from the camera target.

Click and drag to move the camera side to side or up and down.

Rotate the direction of the camera about the camera position to simulate a first-person perspective.

"perspective"

Specifying this interaction style automatically changes the CameraProjection property value to "perspective".

If you specify the CameraProjection value as "orthographic" while this interaction style is specified, the CameraInteractionStyle reverts to the default value of "scene-orbit" for 3-D viewers or "planar" for 2-D viewers.

"walk"This value is useful for simulating a first-person perspective while looking up or down. It is commonly used for flyover views of aerial images or point cloud data.Scroll to move the camera toward or away from the camera target while keeping the z-coordinate of the camera position constant.

Click and drag to move the camera side to side or up and down.

Rotate the direction of the camera about the camera position to simulate a first-person perspective.

"perspective"

Specifying this interaction style automatically changes the CameraProjection property value to "perspective".

If you specify the CameraProjection value as "orthographic" while this interaction style is specified, the CameraInteractionStyle reverts to the default value of "scene-orbit" for 3-D viewers or "planar" for 2-D viewers.

Since R2026a

Angle defining the field of view of the perspective camera, specified as a numeric scalar in the range (0, 180]. This property has no effect when the CameraProjection property value is "orthographic".

Since R2026a

Area in the view of the orthographic camera, specified as a Rectangle object or a 4-element row vector of the form [x y width height] in the world coordinates of the viewer. This property is stored as a Rectangle object. If the specified viewport and the size of the parent of the viewer do not match, the viewer uses a viewport that matches the parent aspect ratio and includes the entire specified region.

This property is intended to be used with 2-D image displays with these characteristics:

  • CameraProjection property value is "orthographic"

  • Camera is pointing towards the positive z-direction

  • CameraUpVector property value points toward the negative y-direction

Use this property to programmatically focus on a known and specific image region. For example, crop a blockedImage object to the viewport area to limit the amount of data that you must read into memory. Alternatively, crop the viewport to generate a thumbnail graphic of, or zoom into, a specific region of an imageshow display. In these cases, setting the CameraViewport value has a similar effect to specifying xlim and ylim on an axes-based imshow display.

Color

expand all

Color of the background, specified as an RGB triplet, a hexadecimal color code, a color name, or a short color name. When you select light mode in MATLAB®, the default color is [0.9608 0.9608 0.9608] if you create the viewer using the viewer2d function and [0 0.251 0.451] if you create the viewer using the viewer3d function. When you select dark mode in MATLAB, the default color is [0.1 0.1 0.1], regardless of the function you use to create the viewer.

RGB triplets and hexadecimal color codes are useful for specifying custom colors.

  • An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1]; for example, [0.4 0.6 0.7].

  • A hexadecimal color code is a character vector or a string scalar that starts with a hash symbol (#) followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case sensitive. Thus, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Color NameShort NameRGB TripletHexadecimal Color CodeAppearance
"red""r"[1 0 0]"#FF0000"

Sample of the color red

"green""g"[0 1 0]"#00FF00"

Sample of the color green

"blue""b"[0 0 1]"#0000FF"

Sample of the color blue

"cyan" "c"[0 1 1]"#00FFFF"

Sample of the color cyan

"magenta""m"[1 0 1]"#FF00FF"

Sample of the color magenta

"yellow""y"[1 1 0]"#FFFF00"

Sample of the color yellow

"black""k"[0 0 0]"#000000"

Sample of the color black

"white""w"[1 1 1]"#FFFFFF"

Sample of the color white

This table lists the default color palettes for plots in the light and dark themes.

PalettePalette Colors

"gem" — Light theme default

Before R2025a: Most plots use these colors by default.

Sample of the "gem" color palette

"glow" — Dark theme default

Sample of the "glow" color palette

You can get the RGB triplets and hexadecimal color codes for these palettes using the orderedcolors and rgb2hex functions. For example, get the RGB triplets for the "gem" palette and convert them to hexadecimal color codes.

RGB = orderedcolors("gem");
H = rgb2hex(RGB);

Before R2024a: Get the hexadecimal color codes using H = compose("#%02X%02X%02X",round(RGB*255)).

Before R2023b: Get the RGB triplets using RGB = get(groot,"FactoryAxesColorOrder").

Example: BackgroundColor="r"

Example: BackgroundColor="green"

Example: BackgroundColor=[0 0.4470 0.7410]

Example: BackgroundColor="#FF8800"

Background gradient is present in the scene, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

This property specifies whether the background is shaded with a gradient from GradientColor to BackgroundColor. When this property is "off", the GradientColor property has no effect.

  • If you create the viewer using the viewer2d function, the default value is "off" to display the image against a solid background.

  • If you create the viewer using the viewer3d function, the default value is "on" to help visualize the volume in 3-D space.

Color of the background gradient shading, specified as an RGB triplet, a hexadecimal color code, a color name, or a short color name. When BackgroundGradient is true, the background is shaded as a gradient from GradientColor to BackgroundColor. When you select light mode in MATLAB, the default color is [0.0667 0.4431 0.7451]. When you select dark mode in MATLAB, the default color is [0.3 0.3 0.3].

RGB triplets and hexadecimal color codes are useful for specifying custom colors.

  • An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1]; for example, [0.4 0.6 0.7].

  • A hexadecimal color code is a character vector or a string scalar that starts with a hash symbol (#) followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case sensitive. Thus, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Color NameShort NameRGB TripletHexadecimal Color CodeAppearance
"red""r"[1 0 0]"#FF0000"

Sample of the color red

"green""g"[0 1 0]"#00FF00"

Sample of the color green

"blue""b"[0 0 1]"#0000FF"

Sample of the color blue

"cyan" "c"[0 1 1]"#00FFFF"

Sample of the color cyan

"magenta""m"[1 0 1]"#FF00FF"

Sample of the color magenta

"yellow""y"[1 1 0]"#FFFF00"

Sample of the color yellow

"black""k"[0 0 0]"#000000"

Sample of the color black

"white""w"[1 1 1]"#FFFFFF"

Sample of the color white

This table lists the default color palettes for plots in the light and dark themes.

PalettePalette Colors

"gem" — Light theme default

Before R2025a: Most plots use these colors by default.

Sample of the "gem" color palette

"glow" — Dark theme default

Sample of the "glow" color palette

You can get the RGB triplets and hexadecimal color codes for these palettes using the orderedcolors and rgb2hex functions. For example, get the RGB triplets for the "gem" palette and convert them to hexadecimal color codes.

RGB = orderedcolors("gem");
H = rgb2hex(RGB);

Before R2024a: Get the hexadecimal color codes using H = compose("#%02X%02X%02X",round(RGB*255)).

Before R2023b: Get the RGB triplets using RGB = get(groot,"FactoryAxesColorOrder").

Example: GradientColor="r"

Example: GradientColor="green"

Example: GradientColor=[0 0.4470 0.7410]

Example: GradientColor="#FF8800"

Lighting

expand all

Light source is enabled, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

This property specifies whether to render the effects of the light source or sources in the Lights property.

Since R2023b

Light sources, specified as a Light object or array of Light objects. Each Light object defines a light source in the scene. By default, Lights specifies one light source above and to the right of the camera.

If you have multiple light sources in a scene, use the Light object properties to specify the state (on or off), position, intensity, and size of each light source. You can enable or disable all light sources simultaneously by specifying the Lighting property.

Since R2023b

Strength of ambient light in the scene, specified as a numeric scalar in the range [0, 1]. This property specifies the amount of ambient light in the scene.

Since R2023b

Strength of diffuse light, specified as a numeric scalar in the range [0, 1]. This property specifies the amount of diffuse light provided by the light sources in the Lights property.

Specify the DiffuseLight property if you have one light source in a scene, or to update all light sources in a multilight scene to the same value. To adjust an individual light in a multilight scene, set the Intensity property of the corresponding Light object in the Lights property.

Color of the light source, specified as an RGB triplet, a hexadecimal color code, a color name, or a short color name. The Viewer object applies the specified color to all light sources in the viewer.

RGB triplets and hexadecimal color codes are useful for specifying custom colors.

  • An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1]; for example, [0.4 0.6 0.7].

  • A hexadecimal color code is a character vector or a string scalar that starts with a hash symbol (#) followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case sensitive. Thus, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.

Color NameShort NameRGB TripletHexadecimal Color CodeAppearance
"red""r"[1 0 0]"#FF0000"

Sample of the color red

"green""g"[0 1 0]"#00FF00"

Sample of the color green

"blue""b"[0 0 1]"#0000FF"

Sample of the color blue

"cyan" "c"[0 1 1]"#00FFFF"

Sample of the color cyan

"magenta""m"[1 0 1]"#FF00FF"

Sample of the color magenta

"yellow""y"[1 1 0]"#FFFF00"

Sample of the color yellow

"black""k"[0 0 0]"#000000"

Sample of the color black

"white""w"[1 1 1]"#FFFFFF"

Sample of the color white

This table lists the default color palettes for plots in the light and dark themes.

PalettePalette Colors

"gem" — Light theme default

Before R2025a: Most plots use these colors by default.

Sample of the "gem" color palette

"glow" — Dark theme default

Sample of the "glow" color palette

You can get the RGB triplets and hexadecimal color codes for these palettes using the orderedcolors and rgb2hex functions. For example, get the RGB triplets for the "gem" palette and convert them to hexadecimal color codes.

RGB = orderedcolors("gem");
H = rgb2hex(RGB);

Before R2024a: Get the hexadecimal color codes using H = compose("#%02X%02X%02X",round(RGB*255)).

Before R2023b: Get the RGB triplets using RGB = get(groot,"FactoryAxesColorOrder").

Example: LightColor="r"

Example: LightColor="green"

Example: LightColor=[0 0.4470 0.7410]

Example: LightColor="#FF8800"

Position of the light source or sources, specified as a 3-element vector of the form [x y z]. Changing the LightPosition property changes the point from which the lights illuminates the scene.

Specify the LightPosition property if you have one light source in a scene, or to update all light sources in a multilight scene to the same value. To adjust an individual light in a multilight scene, set the Position property of the corresponding Light object in the Lights property.

Mode for the light positions, specified as one of these values.

  • "headlight" — Light is at the camera location and moves with the camera.

  • "right" — Light is above and to the right of the camera and moves with the camera. This is the default value.

  • "left" — Light is above and to the left of the camera and moves with the camera.

  • "camera-above" — Light is above the camera and moves with the camera.

  • "target-right" — Light is to the right of the camera target and moves with the camera.

  • "target-left" — Light is to the left of the camera target and moves with the camera.

  • "target-above" — Light is above the camera target and moves with the camera.

  • "target-below" — Light is below the camera target and moves with the camera.

  • "target-behind" — Light is behind the camera target and moves with the camera.

  • "manual" — The light is at the position specified by the LightPosition property. The light does not move with the camera.

  • "auto" — The light moves with the camera.

Setting the LightPosition property changes this property to "manual". Specify the LightPositionMode property if you have one light source in a scene, or to update all light sources in a multilight scene to the same value. To adjust an individual light in a multilight scene, set the PositionMode property of the corresponding Light object in the Lights property.

Denoising

expand all

Since R2023b

Apply edge-preserving denoising, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", the viewer applies edge-preserving denoising to all objects in the viewer. By default, the value is "off". If the viewer contains a Volume object displayed using cinematic rendering, meaning the RenderingStyle property value is "CinematicRendering", the Denoising value automatically changes to "on".

Since R2023b

Denoising degree of smoothing, specified as a numeric scalar in the range [0, 1]. This property affects the visualization only when the Denoising property value is "on". A smaller value preserves details with lower intensity variance, and a larger value smooths neighborhoods with higher intensity variance, such as strong edges.

Since R2023b

Standard deviation of the smoothing filter kernel, specified as a positive integer scalar. This property affects the visualization only when the Denoising property value is "on". A larger value increases the contribution of more distant neighboring pixels, effectively increasing the neighborhood size.

Interactivity

expand all

Interactivity of the volume, specified as "all", "none", or a string array that includes any combination of the strings listed in the table. When specified as "all", the viewer supports all interactions in the table. When specified as "none", the viewer supports no interactions.

Volume InteractionDescription
"zoom"Zoom in on the scene.
"rotate"Rotate the scene.
"pan"Pan across the scene.
"axes"You can click the labels of the orientation axes to snap to an orthogonal view.
"clip"You can further customize the supported clipping interactions with the ClippingInteractions property.
"slice"You can interactively adjust the slice planes of a Volume object when the RenderingStyle property of the object is "SlicePlanes". You can further customize the supported slice plane interactions with the SliceInteractions property.
"crop"You can interactively crop the scene using a rectangular, spherical, or cylindrical 3-D crop region. You can further customize the supported crop interactions with the CropInteractions property.
"scissors"You can interactively crop regions out of the scene using the 3-D scissors tool. The viewer supports this tool when the viewer contains Volume objects. The viewer does not support this tool when the viewer contains one or more Surface or BlockedVolume objects.
"annotate"You can interactively add, edit, and remove 3-D point and line annotations. You can control the placement of annotations with the Annotations property.
  • If you create the viewer using the viewer2d function, the default value is ["zoom" "pan"] to support 2-D zoom and pan interactions.

  • If you create the viewer using the viewer3d function, the default value is "all" to support all interactions.

Interactivity of the slice planes, specified as "all", "none", or a string array that includes any combination of the strings listed in the table. When this value is "none", you cannot interact with the slice planes, but you can still update the planes programmatically. To interact with the slices planes, you must set CurrentObject as an object that supports slice planes.

Slice InteractionDescription
"add"Add new planes by clicking the axes toolbar button.
"remove"Remove planes using right-click.
"rotate"Rotate by dragging the ball.
"translate"Translate planes by dragging the plane surface.

This property affects the visualization only when Interactions is "all" or a string array that contains "slice".

Current object, returned as a child object of the viewer. When an object is added as a child of the viewer, MATLAB sets the CurrentObject property to that object. You can change CurrentObject by setting this property to the handle of another object that is a child of the viewer. When GlobalClipping is false, you can use this property to control which object receives clipping plane interactions.

Rendering quality, specified as one of the values in the table.

ValueDescription
"auto"

Rendering quality automatically adjusts during interactions to improve performance. After the interaction, the rendering quality is restored.

This is the default value when you create the viewer using the viewer3d function.

"low"Low rendering quality with high performance. Use this value when setting properties rapidly and repeatedly.
"medium"

Medium rendering quality, suitable for static and interactive visualization depending on the image data size and GPU capabilities.

This is the default value when you create the viewer using the viewer2d function.

"high"

High rendering quality, at the expense of reduced performance. Use this value when generating high-quality static images.

Context menu, specified as a ContextMenu object created using the uicontextmenu function. Use this property to display a context menu when you right-click an area of the viewer that does not contain any underlying UI components or graphics objects.

To display a context menu when you right-click any portion of a viewer, write code to set the ContextMenu property of all underlying UI components and graphics objects whenever the ContextMenu property of the viewer is set.

For example, this code shows how to create a Viewer object for 3-D display and specify a context menu. The context menu appears when you right-click the viewer.

fig = uifigure;
cm = uicontextmenu(fig);
m1 = uimenu(cm);
viewer = viewer3d(fig,ContextMenu=cm);

Callbacks

expand all

Since R2026b

Camera moved callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes when the camera stops being interactively moved. The callback does not execute when the camera is programmatically moved.

This callback function can access specific information about the camera movement. MATLAB passes this information in a images.ui.graphics.events.CameraMovedEventData object as the second argument to your callback function. All event data properties are read-only. The CameraMovedEventData object has these properties:

PropertyDescription
CameraPosition

Current camera position, returned as a 1-by-3 vector of the form [x y z]

CameraTarget

Current camera target, returned as a 1-by-3 vector of the form [x y z]

CameraUpVector

Current camera up vector, returned as a 1-by-3 vector of the form [x y z]

CameraZoom

Current camera zoom level, returned as a positive scalar

PreviousCameraPosition

Previous camera position, returned as a 1-by-3 vector of the form [x y z]

PreviousCameraTarget

Previous camera target, returned as a 1-by-3 vector of the form [x y z]

PreviousCameraUpVector

Previous camera up vector, returned as a 1-by-3 vector of the form [x y z]

PreviousCameraZoom

Previous camera zoom level, returned as a positive scalar

Example: Synchronize Camera Views Between Two Viewers

This example uses a cell array callback to synchronize two cameras. When you move the camera interactively in one viewer, the callback updates the other viewer programmatically to match.

% Load sample volume data
dataDir = fullfile(toolboxdir("images"),"imdata","BrainMRILabeled");
load(fullfile(dataDir,"images","vol_001.mat"),"vol");

% Create figure containing two side-by-side 3-D viewers
fig = uifigure(Position=[100 100 900 400]);
viewer1 = viewer3d(Parent=fig,Position=[10 10 400 380]);
viewer2 = viewer3d(Parent=fig,Position=[450 10 400 380]);

% Display the volume in both viewers
volshow(vol,Parent=viewer1);
volshow(vol,Parent=viewer2);

% Set up two-way synchronization using a cell array to pass the target viewer
viewer1.CameraMovedFcn = {@syncCameras,viewer2};
viewer2.CameraMovedFcn = {@syncCameras,viewer1};

% Demonstrate interactive and programmatic behavior
disp("Interactive test: Rotate the volume in the first viewer. The second viewer synchronizes.");
disp("Waiting 5 seconds before the programmatic test...");
pause(5);

disp("Programmatic test: Updating the camera position of the first viewer via code.");
disp("The second viewer does not synchronize because programmatic updates do not trigger the callback.");

% Update the camera position of the first viewer programmatically. 
% This action does not trigger the CameraMovedFcn callback.
viewer1.CameraPosition = [100 200 300]; 


% Callback function to synchronize camera properties
function syncCameras(~,evt,targetViewer)

    % Update target viewer camera properties programmatically.
    % This programmatic update does not trigger the CameraMovedFcn callback of the target viewer, which safely prevents an infinite loop.
    targetViewer.CameraPosition = evt.CameraPosition;
    targetViewer.CameraTarget   = evt.CameraTarget;
    targetViewer.CameraUpVector = evt.CameraUpVector;
    targetViewer.CameraZoom     = evt.CameraZoom;

end

Since R2026b

Camera moving callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes continuously while the camera is being interactively moved. The callback does not execute when the camera is programmatically moved.

This callback can execute frequently during camera interaction. Keep the callback function lightweight to avoid performance issues or UI unresponsiveness.

This callback function can access the same information as CameraMovedFcn. MATLAB passes this information as the second argument to your callback function in images.ui.graphics.events.CameraMovedEventData. All event data properties are read-only. For a list of the event data properties, see the CameraMovedFcn property.

Since R2026b

Annotation added callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes when an annotation is interactively added to the viewer. The callback does not execute when the annotation is programmatically added. For multi-click annotations, such as polygons and polylines, this callback executes once after the annotation is complete.

Use the uidraw function to draw annotations interactively. For a list of supported Region of Interest (ROI) annotations and their availability in the viewer toolbar, see the Annotations property.

This callback function can access information about the added annotation. MATLAB passes this information as the second argument to your callback function in images.ui.graphics.events.AnnotationAddedEventData. All event data properties are read-only. The AnnotationAddedEventData object has these properties:

PropertyDescription
Annotation

Handle to the annotation that was added

Example: Label New Annotations in Custom App

This example shows how to create an app for interacting with a 3-D volume. The app includes a drop-down menu and a button that call the uidraw function to create different Region of Interest (ROI) annotations. When you finish drawing an annotation, a callback function assigns a label based on the annotation type.

function customROIApp3D
% Create app for drawing ROI annotations in a 3-D viewer.

% Create application window
fig = uifigure(Name="3-D Brain ROI Annotation App", ...
    Position=[100 100 800 500]);

% Create control panel
leftPanel = uipanel(fig,Title="Drawing Tools", ...
    Position=[10 10 180 480]);

% Create 3-D viewer
viewer = viewer3d(Parent=fig,Position=[200 10 590 480]);

% Load and display volume
load(fullfile(toolboxdir("images"),"imdata", ...
    "BrainMRILabeled","images","vol_001.mat"),"vol");
volshow(vol,Parent=viewer);

% Set callback for added annotations using function handle
viewer.AnnotationAddedFcn = @labelAnnotation;

% Create ROI selection label
uilabel(leftPanel,Position=[10 410 160 22], ...
    Text="Select ROI shape:");

% Create drop-down list of ROI shapes
shapeDropdown = uidropdown(leftPanel, ...
    Position=[10 380 160 22], ...
    Items=["point" "line" "polyline" "polygon" ...
    "rectangle" "circle" "ellipse" "freehand" "angle"]);

% Create button for drawing selected ROI
uibutton(leftPanel,Position=[10 340 160 30], ...
    Text="Draw Shape", ...
    ButtonPushedFcn=@(~,~) uidraw(viewer,shapeDropdown.Value,Wait="none"));

% Create instruction label
uilabel(leftPanel,Position=[10 200 160 100], ...
    WordWrap="on", ...
    Text=["Select an ROI shape, click Draw Shape, and then " ...
    "draw in the volume. The callback assigns a label " ...
    "to the annotation."]);
end

function labelAnnotation(src,evt)
% Assign label to added annotation.

% Get added annotation
roi = evt.Annotation;

% Extract annotation type name
roiType = class(roi);
roiType = extractAfter(roiType,"roi.");

% Count existing annotations of the same type
allAnnotations = src.Annotations;
count = sum(arrayfun(@(x) isa(x,class(roi)),allAnnotations));

% Assign label
roi.Label = sprintf("%s %d",roiType,count);

% Display message in Command Window
fprintf("Added annotation: %s\n",roi.Label);
end

Since R2026b

Annotation moved callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes when an annotation is interactively moved in the viewer. The callback does not execute when the annotation is programmatically moved. The callback fires after the movement is complete.

This callback function can access specific information about the annotation movement. MATLAB passes this information in a images.ui.graphics.events.AnnotationMovedEventData object as the second argument to your callback function. All event data properties are read-only. The AnnotationMovedEventData object has these properties:

PropertyDescription
Annotation

Handle to the annotation that was moved

PreviousPosition

Previous position of the annotation

Since R2026b

Annotation removed callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes when an annotation is interactively removed from the viewer via the context menu. The callback does not execute when the annotation is programmatically deleted. The annotation object remains valid during callback execution.

This callback function can access specific information about the removed annotation. MATLAB passes this information in a images.ui.graphics.events.AnnotationRemovedEventData object as the second argument to your callback function. All event data properties are read-only. The AnnotationRemovedEventData object has these properties:

PropertyDescription
Annotation

Handle to the annotation that was removed (still valid during callback execution)

Example: Log Annotation Removal

The example displays a volume with a sample point annotation and sets a callback function that logs a confirmation message to the Command Window when the annotation is deleted.

% Create viewer
viewer = viewer3d;

% Load and display volume
load(fullfile(toolboxdir("images"),"imdata", ...
    "BrainMRILabeled","images","vol_001.mat"));
volshow(vol,Parent=viewer);

% Add sample annotation
pt = images.ui.graphics.roi.Point( ...
    Parent=viewer,Position=[64 64 13],Label="Center Point");
viewer.Annotations = pt;

% Set annotation removed callback using a function handle
viewer.AnnotationRemovedFcn = @(src,evt) confirmRemoval(evt);

function confirmRemoval(evt)
% Display removed annotation label.

roi = evt.Annotation;
roiLabel = roi.Label;

if isempty(roiLabel)
    roiLabel = extractAfter(class(roi),"roi.");
end

fprintf("Removed annotation: %s\n",roiLabel);
end

Since R2026b

Object clicked callback, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle and subsequent elements are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB command or function, which is evaluated in the base workspace (not recommended).

This callback executes when any object is interactively clicked in the viewer. The callback executes when the mouse button is released, and only if the following conditions are met:

  • The viewer toolbar is not in a mode such as pan or rotate

  • The pointer does not move during the click (click-and-drag does not trigger the callback)

  • For viewer children (Volume, BlockedVolume, Surface, or Image), the Pickable property is 'on' or 'visible'

Note

Interactions with region of interest (ROI) annotations do not trigger this callback. Interactive annotations consume mouse click events to support dragging and reshaping. Annotations with Interactions set to 'none' do not consume click events, allowing clicks to pass through to underlying displayed elements such as volumes or surfaces.

This callback function can access specific information about the click. MATLAB passes this information in a images.ui.graphics.events.ObjectInfoEventData object as the second argument to your callback function. All event data properties are read-only. The ObjectInfoEventData object has these properties:

PropertyDescription
Object

Handle to the clicked element. Returns an empty array if the click occurs on empty space

ClickType

Type of click: 'left', 'right', 'double', 'middle', 'ctrl-left', 'shift-left', or 'alt-left'

Position

Click location in 3-D world coordinates, returned as a 1-by-3 vector [x y z]. For 2-D images, the z-coordinate is always 1. For volumes with transparent rendering, this location can be limited in accuracy

Example: Interactively Highlight Clicked Medical Data

This example shows how to use the ObjectClickedFcn callback to identify and visually isolate objects in a 3-D scene. The app displays an MRI brain volume alongside two segmented anatomical surfaces.

When you click an object, the callback extracts the exact 3-D coordinates from the event data's Position property and prints them to the Command Window. The callback then updates the display by setting the clicked element to full opacity and reducing the opacity of the remaining elements.

% Load the MRI volume and its segmented label data
dataDir = fullfile(toolboxdir("images"),"imdata","BrainMRILabeled");
load(fullfile(dataDir,"images","vol_001.mat"),"vol");
load(fullfile(dataDir,"labels","label_001.mat"),"label");

% Create the 3-D viewer
viewer = viewer3d(BackgroundColor="white",BackgroundGradient="off");

% Add the main brain volume
hVolume = volshow(vol,Parent=viewer,RenderingStyle="GradientOpacity");
hVolume.Tag = "Brain Volume";
hVolume.Pickable = "on";

% Create surface meshes from the label data (e.g., segmented tumors or tissue)
label1 = (label == 1);
surf1 = surfaceshow(label1,Parent=viewer,Alpha=0.3);
surf1.Tag = "Segment 1";
surf1.Pickable = "on";

label3 = (label == 3);
surf3 = surfaceshow(label3,Parent=viewer,Alpha=0.3);
surf3.Tag = "Segment 3";
surf3.Pickable = "on";

% Set the callback to trigger our custom logic
viewer.ObjectClickedFcn = @highlightObject;

disp("Interactive test: Click the volume or the surface segments.");
disp("Look at the Command Window for the exact 3-D coordinates of your click.");

% Callback function
function highlightObject(~,evt)

    % Do nothing if the user clicked empty space
    if isempty(evt.Object)
        return;
    end

    % Print the position data to the console
    coords = evt.Position;
    fprintf("You clicked %s at World Coordinates: [%.1f, %.1f, %.1f]\n", ...
        evt.Object.Tag,coords(1),coords(2),coords(3));

    % Get all objects in the viewer
    allObjects = evt.Object.Parent.Children;

    % Loop through and visually isolate the clicked object
    for i = 1:length(allObjects)
        currentObj = allObjects(i);

        if currentObj == evt.Object
            % Make the clicked object fully opaque
            setTransparency(currentObj,1.0);
        else
            % Dim everything else to 10% opacity
            setTransparency(currentObj,0.1);
        end
    end
end

% Helper function to safely change transparency for different object types
function setTransparency(obj,targetAlpha)
    if isa(obj,"images.ui.graphics.Volume")
        % Volumes use an Alphamap array
        obj.Alphamap = linspace(0,targetAlpha,256);
    elseif isprop(obj,"Alpha")
        % Surfaces use the Alpha property
        obj.Alpha = targetAlpha;
    end
end

Cropping

expand all

Since R2023b

Position of the crop box in world coordinates, specified as one of the options in the table. Use the CropInteractions property to specify whether you can change this region interactively. This property affects the visualization only when Interactions is "all" or a string array that contains "crop".

ShapeValue
Rectangular2-by-3 numeric matrix of the form [xmin ymin zmin; xmax ymax zmax], where the first and second rows specify the minimum and maximum coordinates of the crop box, respectively.

Spherical (since R2024b)

4-element numeric row vector of the form [x y z radius], where (x, y, z) and radius specify the center and radius of the sphere, respectively.

Cylindrical (since R2024b)

5-element numeric row vector of the form [x y z radius height], where (x, y, z), radius, and height specify the center, radius, and height of the cylinder, respectively.

Since R2024b

Crop mode for the crop region defined by CropRegion, specified as "inclusive" or "exclusive". When set to "inclusive", objects inside the crop region are visible and objects outside the crop region are hidden. When set to "exclusive", objects outside the crop region are visible and objects inside the crop region are hidden.

Data Types: char | string

Since R2023b

Interactivity of the crop region, specified as "all", "none", or a string array that includes any combination of the strings listed in the table. When specified as "all", the viewer supports all interactions in the table. When specified as "none", you cannot interact with the crop region, but you can still update the crop region programmatically by specifying the CropRegion property.

Crop InteractionDescription
"add"

Add a new rectangular crop region from the viewer toolbar by selecting the crop box icon Crop box icon. You can only have one crop region in a viewer at a time.

While you can add a rectangular crop region either from the toolbar or programmatically, to add a spherical or cylindrical crop region, you must programmatically specify the CropRegion property.

"remove"Remove crop region using right-click.
"move"Resize and move the crop region. Resize the crop region by dragging the surface of the crop region. Move the crop region by holding Ctrl while you drag the faces of the crop region.

This property affects the visualization only when Interactions is "all" or a string array that contains "crop".

Clipping Planes

expand all

Clipping planes in the scene, specified as an N-by-4 matrix, where each row corresponds to the equation for a clipping plane. The maximum number of clipping planes, N, is six. When GlobalClipping is true, these clipping planes are applied to all objects in the scene, irrespective of any clipping planes set locally on each object. Each clipping plane is specified as a 1-by-4 vector, in world coordinates, following the Hessian normal form where the first three values represent the normal vector of the plane and the fourth value is the signed distance from the origin to the plane.

Use global clipping planes, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", the planes specified by the ClippingPlanes property are applied to all objects. When this value is "off", the ClippingPlanes property has no effect and the clipping planes from each object are individually applied.

Clipping plane behavior with multiple planes, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", only intersecting or overlapping regions of all clipping planes are clipped. When this value is "off", a region is clipped if it is clipped by any clipping plane. Set ClipIntersection to "on" to use multiple planes to remove a single quadrant of an object.

Interactivity of the clipping planes, specified as "all", "none", or a string array that includes any combination of strings listed in the table. When specified as "all", all interactions are allowed. When specified as "none", no interactions are allowed.

When this value is "none", you cannot interact with the clipping planes, but you can still update the planes programmatically.

Clipping InteractionDescription
"add"Add new planes by clicking the axes toolbar button.
"remove"Remove planes using right-click.
"rotate"Rotate by dragging the ball.
"translate"Translate planes by dragging the plane surface.

This property affects the visualization only when Interactions is "all" or a string array that contains "clip".

Viewer Annotations

expand all

Toolbar visibility, specified as "on", "off", or "hover". When this value is "on", the toolbar is always visible. When this value is "off", the toolbar is not visible. When this value is "hover" (since R2025a), the toolbar is visible when you position the pointer inside the viewer window, and hidden when the pointer is outside the viewer window.

The toolbar contains the interactions specified by the Interactions property. You can still use the interactions specified by the Interactions property when the toolbar is not visible. To prevent all interaction on the viewer, set Interactions to "none".

Since R2025a

Title for viewer, specified as a string scalar or character vector. The title appears in the top center of the viewer window, within the display.

Since R2024a

Annotations in the scene, specified as an array of ROI annotation objects. You can create interactive annotation objects from the viewer toolbar, by using the uidraw function, or by using the corresponding object creation function. You can create static annotation objects by using the uiannotate function, or by using the corresponding object creation function. To display an ROI annotation you create by using its creation function, add it to the Annotations property of a Viewer object.

This table summarizes options for creating ROI annotations shapes:

ShapeAnnotation TypeViewer Toolbar Supportuidraw or uiannotate SyntaxObject Creation Function
Line (since R2024a)Interactive2-D and 3-Duidraw(viewer,"line")images.ui.graphics.roi.Line
Point (since R2024a)Interactive2-D and 3-Duidraw(viewer,"point")images.ui.graphics.roi.Point
Rectangle (since R2026a)Interactive2-D onlyuidraw(viewer,"rectangle")images.ui.graphics.roi.Rectangle
Circle (since R2026a)Interactive2-D onlyuidraw(viewer,"circle")images.ui.graphics.roi.Circle
Polygon (since R2026a)Interactive2-D onlyuidraw(viewer,"polygon")images.ui.graphics.roi.Polygon
Angle (since R2026a)Interactive2-D onlyuidraw(viewer,"angle")images.ui.graphics.roi.Angle
Polyline (since R2026a)InteractiveNoneuidraw(viewer,"polyline")images.ui.graphics.roi.Polyline
Freehand (since R2026a)InteractiveNoneuidraw(viewer,"freehand")images.ui.graphics.roi.Freehand
Ellipse (since R2026a)InteractiveNoneuidraw(viewer,"ellipse")images.ui.graphics.roi.Ellipse
Rectangles (since R2026b)StaticNoneuiannotate(viewer,"rectangle",position)images.ui.graphics.roi.static.Rectangles
Circles (since R2026b)StaticNoneuiannotate(viewer,"circle",position)images.ui.graphics.roi.static.Circles
Polylines (since R2026b)StaticNoneuiannotate(viewer,"polyline",position)images.ui.graphics.roi.static.Polylines
Lines (since R2026b)StaticNoneuiannotate(viewer,"line",position)images.ui.graphics.roi.static.Lines
Points (since R2026b)StaticNoneuiannotate(viewer,"point",position)images.ui.graphics.roi.static.Points
Cuboids (since R2026b)StaticNoneuiannotate(viewer,"cuboid",position)images.ui.graphics.roi.static.Cuboids
Ellipses (since R2026b)StaticNoneuiannotate(viewer,"ellipse",position)images.ui.graphics.roi.static.Ellipses
Arrows (since R2026b)StaticNoneuiannotate(viewer,"arrow",position)images.ui.graphics.roi.static.Arrows
Spheres (since R2026b)StaticNoneuiannotate(viewer,"sphere",position)images.ui.graphics.roi.static.Spheres
Ellipsoids (since R2026b)StaticNoneuiannotate(viewer,"ellipsoid",position)images.ui.graphics.roi.static.Ellipsoids
Cylinders (since R2026b)StaticNoneuiannotate(viewer,"cylinder",position)images.ui.graphics.roi.static.Cylinders
Plusses (since R2026b)StaticNoneuiannotate(viewer,"plus",position)images.ui.graphics.roi.static.Plusses

Tooltip, specified as a string scalar, string array, character vector, cell array of character vectors, or categorical vector. Use this property to display a message when the user hovers the pointer over the component at run time. To display multiple lines of text, specify a cell array of character vectors or a string array. Each element in the array becomes a separate line of text. If you specify this property as a categorical vector, MATLAB uses the values in the vector, not the full set of categories.

Since R2025a

Display object information, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", the lower-left corner of the viewer displays a zoomed in view and information about the point beneath the pointer. You can interactively toggle the visibility of the information display from the viewer context menu.

  • If you create the viewer using the viewer2d function, the default value is "on".

  • If you create the viewer using the viewer3d function, the default value is "off".

You cannot display object information and the orientation axes simultaneously. If you specify DisplayInfo as "on", the OrientationAxes value changes to "off". If you specify OrientationAxes as "on", then DisplayInfo changes to "off".

You can toggle whether the tool displays information about a specific child object by setting the Pickable property of that object. Child objects can be Image, Volume, BlockedVolume, or Surface objects.

Display the orientation axes, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", the lower-left corner of the viewer displays the orientation axes. If no objects are loaded in the viewer, the orientation axes is not visible.

  • If you create the viewer using the viewer2d function, the default value is "off".

  • If you create the viewer using the viewer3d function, the default value is "on".

You cannot display the orientation axes and object information simultaneously. If you specify OrientationAxes as "on", the DisplayInfo value changes to "off". If you specify DisplayInfo as "on", then OrientationAxes changes to "off".

Display box outline around scene boundary, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

When this value is "on", a box is displayed that fits around every object in the scene. If no 3-D objects are loaded in the viewer, the box is not visible.

Display scale bar in the lower-right corner, specified as "on" or "off", or as a numeric or logical 1 (true) or 0 (false). A value of "on" is equivalent to true, and "off" is equivalent to false. The value is stored as an on/off logical value of type OnOffSwitchState.

Control the style of the scale bar by using the ScaleBarStyle property.

Since R2025a

Style of the scale bar, specified as one of the strings in the table. Control the visibility of the scale bar by using the ScaleBar property.

  • If you create the viewer using the viewer2d function, the default value is "zoom".

  • If you create the viewer using the viewer3d function, the default value is "measure".

ValueDescription
"zoom"Display a scale bar with the zoom level of the image. The zoom level is based on a combination of available screen size, the image size, and the viewer camera zoom level. A scale bar zoom level of 100% indicates that one screen pixel displays one data pixel, or one unit in world coordinates if you specify the Transformation property of the child Image, Volume, or BlockedVolume.
"measure"Display a measurement scale bar with units specified by the SpatialUnits property.

Spatial units for the viewer, specified as a string scalar. Use this value to change the units label associated with viewer display tools, such as the scale bar and point and line annotations. For example, if you specify the Transformation property of a Volume object to display an object in millimeters, you can optionally specify SpatialUnits as "mm".

  • If you create the viewer using the viewer2d function, the default value is "pixels".

  • If you create the viewer using the viewer3d function, the default value is "voxels".

Parent/Child

expand all

Parent of the viewer, specified as a Figure object created using the uifigure function, or a Panel, GridLayout, or Tab object whose parent is a figure created using the uifigure function. You can use the uipanel, uigridlayout, and uitab functions to create the corresponding objects.

If you do not specify a parent when you create the viewer, MATLAB calls the uifigure function to create a new Figure object that serves as the parent container.

A GridLayout object is the recommended parent when you want to build an app in App Designer, or when you want to add and position other UI components in a figure with the viewer. When the parent is a GridLayout object, you can adjust the layout of the viewer using the Layout property.

This property is read-only.

Children of the viewer, returned as an array of Image, Volume, BlockedVolume, and Surface objects or as an empty GraphicsPlaceholder array. Setting this property has no effect.

Position

expand all

Size and location of the viewer relative to the parent object, excluding the margins for decorations such as axis labels and tick marks, specified as a 4-element vector of the form [left bottom width height]. By default, the viewer is positioned to span the entire parent container.

Note

Setting this property has no effect when the parent of the viewer is a GridLayout object.

Position units, specified as 'pixels', 'normalized', 'inches', 'centimeters', 'points', or 'characters'. This value specifies units for the Position property. The recommended value is 'pixels'. To manage the position of multiple UI components in a parent, create a GridLayout object using uigridlayout.

To specify units for the viewer display tools, such as the scale bar and point and line annotations, see SpatialUnits.

Layout options, specified as a GridLayoutOptions object. This property specifies layout options only when the parent of the viewer is a GridLayout object. If the parent of the viewer is not a grid layout (for example, when the parent is a figure or panel), then this property is empty and has no effect.

You can place the viewer in the desired row and column of the grid by setting the Row and Column properties of the GridLayoutOptions object. For example, this code places a viewer in the third row and second column of its parent grid.

g = uigridlayout([4 3]);
viewer = viewer3d(g);
viewer.Layout.Row = 3;
viewer.Layout.Column = 2;

To make the viewer span multiple rows or columns, specify the Row or Column property as a 2-element vector. For example, this viewer spans columns 2 through 3.

viewer.Layout.Column = [2 3];

Version History

Introduced in R2022b

expand all