MATLAB: How to fix the vertices of a polygon created by IMPOLY so that they can not be changed in the figure

MATLAB

I have a polygon created using IMPOLY and I want to:
1. Fix the positions of the vertices in relation to one another so that the shape of the polygon can not be altered.
2. Fix the position of the polygon so that it can not be dragged across the figure.

Best Answer

To fix the position of the vertices in relation to one another, one can use the SETVERTICESDRAGGABLE function to set the property to 'false'.
To constrain the polygon to be immobile in the figure, use the MAKECONSTRAINTORECTFCN and the SETPOSITIONCONSTRAINTFCN functions to create the minimum rectangular bounding box around the polygon, and to constrain the polygon to be in that rectangle.
The following code demonstrates how to use these functions:
figure, imshow('gantrycrane.png');
position = [188,30; 189,142; 93,141; 13,41; 14,29];
h = impoly(gca,position);
setColor(h,'yellow');
% Use setVerticesDraggable to 'false' = logical(0); so that the vertices
% can not be individually dragged.
setVerticesDraggable(h, logical(0))
% Constrain the polygon to the smallest rectangle that can be drawn around
% its vertices.
xmin = min(position(:,1));
xmax = max(position(:,1));
ymin = min(position(:,2));
ymax = max(position(:,2));
fcn = makeConstrainToRectFcn('impoly',[xmin xmax],[ymin ymax]);
setPositionConstraintFcn(h,fcn);