File: ef230-2023-08/www/examples/move_transparent_object.m Download
% example to demonstrate animating an object
% with a transparent background
% EF 230 Spring, 2014 WRS

close all;

% load an image of a bridge - this one happens to be an indexed image so
% we load both the image data (i) and colormap (c)
[i,c] = imread('');
% convert the colomapped image to an rgb image
bridge = ind2rgb(i,c);
% load an image of the car - this one has a white background
car =  imread('');

% show the bridge on the figure
hold all

% create a 2D matrix of ones and zeros with ones where the image is to be transparent
% for this one we compare each pixel's color information to the upper left pixel color
% MATLAB calls this the alphadata for the image
A = car(:,:,1)~=car(1,1,1) | car(:,:,2)~=car(1,1,2) | car(:,:,3)~=car(1,1,3);

% show the image (with alphadata set)
% save its handle so it can be moved later on
h=image([d d+50],[155 170],car,'alphadata',A);

% this loop moves the image
% note that you should move it rather than redraw it
for d=50:5:500
    set(h,'XData',[d d+50]); % set the x position of the image to a new value