Back

CreateImage

Hello World

Image controls can be used to display images such like png, jpg or gif.
Just pass the file path and you're done.

img = app.CreateImage( file, width, height, options, pxw, pxh ) → app object: Image

Without the width and height dimensions the image will be shown without any scaling.

Example - Original Size

function OnStart()
{
    lay = app.CreateLayout( "Linear", "VCenter,FillXY" );

    img = app.CreateImage( "/Sys/Img/Droid1.png" );
    img.SetOnTouch( img_OnTouch );
    lay.AddChild( img );


    app.AddLayout( lay );
}

function img_OnTouch( ev )
{
    if( ev.action=="Down" )
        app.ShowPopup( "Ouch!" );
}
    Copy     Copy All       Run      

If you specify one of them and leave the other null, -1 or blank, it will be scaled so that the aspect ratio is kept.

Example - Maintain Aspect

function OnStart()
{
    lay = app.CreateLayout( "Linear", "VCenter,FillXY" );

    img = app.CreateImage( "/Sys/Img/Droid1.png", 0.5, -1 );
    img.SetOnTouch( img_OnTouch );
    lay.AddChild( img );


    app.AddLayout( lay );
}

function img_OnTouch( ev )
{
    if( ev.action=="Down" )
        app.ShowPopup( ev.x[0] + ", " + ev.y[0], "Short" );
}
    Copy     Copy All       Run      

And if you specify both parameters it will be scaled to your wishes.

Example - Stretched

function OnStart()
{
    lay = app.CreateLayout( "Linear", "VCenter,FillXY" );

    img = app.CreateImage( "/Sys/Img/Droid1.png", 0.5, 0.7 );
    img.SetOnTouch( img_OnTouch );
    lay.AddChild( img );


    app.AddLayout( lay );
}

function img_OnTouch( ev )
{
    if( ev.action=="Down" )
        app.ShowPopup( "Aaaargh!" );
}
    Copy     Copy All       Run      

If you want images to depress like buttons if touched you can use the “Button” option.

Example - Button

function OnStart()
{
    lay = app.CreateLayout( "linear", "VCenter,FillXY" );

    btn = app.CreateImage( "/Sys/Img/Hello.png", 0.2, -1, "button" );
    btn.SetOnTouchUp( btn_OnTouch );
    lay.AddChild( btn );

    app.AddLayout( lay );
}

function btn_OnTouch()
{
    app.ShowPopup( "Hello World!" );
    app.Vibrate( "0,100,30,100,50,300" );
}
Copy All       Run      

Drawing on Images

Images are also useful for drawing basic shapes and other images on it and therefore for creating dynamic animations or even basic games. To create an empty image you can pass null as file parameter.

This way you can also specify a fixed pixel size to the image you can use the “fix” option and pass values for the pxw and pxh parameters.

img = app.CreateImage( null, 0.8, 0.5, "fix", 20, 20 );
img.DrawLine( 0, 0, 1, 1 );

If you dislike the anti-alias effect you can apply the “alias” option on a higher resolution image and draw a low-resolution image on it:

img2 = app.CreateImage( null, .8, .5, "alias" );
img2.DrawImage( img, 0, 0, 1, 1, 0 );

There are a whole bunch of drawing methods defined here. Some of the were already used above. You can draw lines, rectangles, circles and other images, just to name a few. You can even draw a transformed image using an transformation matrix. Check out the Draw* methods in the method list below to get more details about all drawing functions.

Example - Draw Shapes

function OnStart()
{
    lay = app.CreateLayout( "Linear", "VCenter,FillXY" );

    img = app.CreateImage( null, 0.8, 0.8 );
    lay.AddChild( img );

    img.SetColor( "#8888ff" );
    img.SetPaintColor( "#ff0000" );
    img.DrawCircle( 0.5, 0.5, 0.1 );
    img.DrawRectangle( 0.7, 0.7, 0.1, 0.75 );


    app.AddLayout( lay );
}
    Copy     Copy All       Run      

Drawing on Images fast

If you have many draw operations to perform at runtime (ie. for games) you might want to disable the automatic canvas update after each Draw* call using the SetAutoUpdate method. To force the rendering now, you have to call Update.

Another way to increase the animation speed is using the NoDom configuration. This will disable html and js Dom elements in your app that consume a lot of resources, but app functions can still be used.
For animations you can then use the Animate function of the app object which calls a function for a given amount per second. Note that the canvas still needs some time to refresh - so going over 60 fps makes no sense at all.

Example - Advanced Clock Animating

cfg.No_Dom, cfg.Portrait;

var wh;

function OnStart()
{
    lay = app.CreateLayout( "linear", "VCenter,FillXY" );

    // clock pointer
    ptr = app.CreateImage( null, 0.1, 0.1, "fix,alias", 30, 30 );
    ptr.SetTextSize( 4.3 );

    // image aspect ratio for drawing square images
    wh = ptr.GetAbsWidth() / ptr.GetAbsHeight();

    // main canvas
    img = app.CreateImage( null, 1, 1, "alias" );
    img.SetPaintStyle( "line" );
    img.SetAutoUpdate( false );
    img.SetLineWidth( 15 );
    lay.AddChild( img );

    app.AddLayout( lay );

    app.SetDebug( "console" );
    app.Animate( OnAnimate, 40 );
}

function OnAnimate( time, dtime )
{
    time = Date.now();

    // calculate pointer position from current time
    var secs = time / 1000;
    var angle = Math.PI * secs / 2 + Math.abs( Math.sin( Math.PI * secs ));
    var px = 0.5 + 0.5 * Math.cos( angle );
    var py = 0.5 + 0.5 * Math.sin( angle );

    // get current datetime
    var hrs = Math.floor( secs / 3600 ) % 60;
    var min = Math.floor( secs / 60 ) % 60;
    var sec = Math.floor( secs ) % 60;
    var time = min + ":" + sec;

    // measure text dimensions for centering
    var tsize = ptr.MeasureText( time );
    var tx = (1 - tsize.width ) / 2;
    var ty = (1 + tsize.height) / 2;

    // draw pointer and datetime text
    ptr.Clear();
    ptr.SetPaintColor( "red" );
    ptr.DrawLine( .5, .5, px, py );
    ptr.SetPaintColor( "white" );
    ptr.DrawText( time, tx, ty );

    // render
    img.Clear();
    img.DrawCircle( .5, .5, .48 );
    img.DrawImage( ptr, 0, (1 - wh) / 2, 1, wh );
    img.Update();
}
Copy All       Run      

Methods

The following methods are available on the Image object:

Clear()
DrawImage( image, x, y, w, h, angle, mode )
DrawLine( x1, y1, x2, y2 )
DrawPoint( x, y )
DrawText( txt, x, y )
Focus()
GetAbsHeight() → Number: integer
GetAbsWidth() → Number: integer
GetName() → String
GetParent() → app object
GetPixelColor( x, y ) → List: [ red, green, blue ]
GetPixelData( format, left, top, width, height ) → String: base64 encoded
GetPosition( options ) → Object: { left, top, right, bottom }
GetType() → String: “Image”
GetVisibility() → String: “Show” or “Hide” or “Gone”
Gone()
Hide()
MeasureText( txt ) → Object: { width, height }
Method( name, types, p1, p2, p3, p4 ) → all types
Move( x, y )
Reset()
Scale( x, y )
SetScale( x, y )
Show()
Skew( x, y )
Update()
Boolean
app object
List
Number
String
unknown
Number: angle in degrees (0..360)
Number: 0-255
Number: factor
Number: fraction (0..1)
Number: integer
Number: milliseconds
Number: pixel
Number: -180..180
Number: -100..100
Number: 0..100
Number: corner 1
Number: corner 2
Number: width relative
Number: percent: for jpg files
Number: 0..0.99 or 1..256
String:
  hexadecimal: “#rrggbb”, “#aarrggbb”
  colourName: “red”, “green”, ...
String: comma “,” separated
String: file path or content:// uri
String: path to file ( “/absolute/...” or “relative/...” )
String: comma “,” separated: “fix”, “alias”, px, Button, “ScaleCenter”, async, “FontAwesome”, “Resize”, “TouchThrough”, Icon, “wallpaper”, NoPlay
String: “NewsPaper” or “Jelly” or “Flash” or “RubberBand” or “Swing” or “TaDa” or “Bounce” or “Fall” or “FallRotate” or
String: “ADD” or “CLEAR” or “DARKEN” or “DST” or “DST_ATOP” or “DST_IN” or “DST_OUT” or “DST_OVER” or “LIGHTEN” or “MULTIPLY” or “OVERLAY” or “SCREEN” or “SRC” or “SRC_ATOP” or “SRC_IN” or “SRC_OUT” or “SRC_OVER” or “XOR”
String: “px”
String: “rawbase64” or “pngbase64” or “jpgbase64”
String: “screen”, “px”
String: “left-right” or “right-left” or “top-bottom” or “bottom-top” or “bl-tr” or “br-tl” or “tl-br” or “tr-bl”
String: “repeat”
String: “Add” or “Multiply” or “clear” or “darken” or “lighten” or “overlay” or “screen” or “xor” or “src_in” or “src_out” or “src_atop” or “src_over” or “dst_in” or “dst_out” or “dst_atop” or “dst_over”
String: “rescale”
String: “px” or “sp” or “dip” or “mm” or “pt”
String: “Fill” or “Line”
String: base64 encoded: “<rawbase64>” or “data:image/jpg;base64,<jpgbase64>”, “data:image/png;base64,<pngbase64>”
String: “px”, “icon”, “resize” or “rescale” or “square”, fix
String: “px” or “sp” or “dip” or “dp” or “mm” or “pt”
String: “Show” or “Hide” or “Gone”
String: “Linear.None” or “Quadratic.In/Out” or “Cubic.In/Out” or “Quartic.In/Out” or “Quintic.In/Out” or “Sinusoidal.In/Out” or “Exponential.In/Out” or “Circular.In/Out” or “Elastic.In/Out” or “Back.In/Out” or “Bounce.In/Out”
String: path to file or folder ( “/absolute/...” or “relative/...” )
app object: Image
Object: { source, action, count, x: [ x1, x2, x3 ], y: [ y1, y2, y3 ] }
Object: { source, action, count, x: [ x1, x2, x3 ], y: [ y1, y2, y3 ] }
Object: { source, action, count, x: [ x1, x2, x3 ], y: [ y1, y2, y3 ] }
Object: { source, action, count, x: [ x1, x2, x3 ], y: [ y1, y2, y3 ] }
Object: { x, y, w, h, sw, sh, rot }
app object: CreateImage
List: [a, b, c, d, tx, ty]
List: [ data ]
List: boolean,char,byte,short,int,long,float,double,String,CharSequence,...
function( type )
function( img )
function( src )
function( event )
function( event )
function( event )
function( event )
function()
img.AdjustColor
Adjust the visual color effect of the control by setting the Hue (by angle in degrees in a color circle), the saturation, brightness and contrast of the control.
img.Animate
Animates the control.

There are
    “in”-Animations which are used to show objects from hidden state
    “out”-animations which are used to hide objects in visible state and
    “static”-animations which keep the visible state.
img.Clear
Clears everything on the image except the background.
img.ClearFocus
Removes the focus of the control so that the user no longer has immediate access to it.
img.DrawArc
Draws an elliptical arc by specifying the corners of the surrounding rectangle and the angle range of the arc to be drawn.
img.DrawCircle
Draws a Circle.
img.DrawFrame
Draws the frame on a given time of a loaded gif file.
img.DrawImage
Draws an Image.
See Android Developers for 'mode' info
img.DrawImageMtx
Draws an image with a 2d transformation matrix.
img.DrawLine
Draws a line.
img.DrawPoint
Draws a single pixel.
img.DrawRectangle
Draws a rectangle.
img.DrawSamples
Draws a vertically centered graph in relation to the specified range in both direction.
The sample value 0 would be vertically centered, -range at the top and range at the bottom.
The sample x positions are evenly distributed over the whole image width.
img.DrawText
Draws a text.
img.Flatten
Applies certain modifications to the image data, such as translate, scale, skew or alpha.
img.Focus
Set the focus to the control so that the user can interact with it immediately.
img.GetAbsHeight
Get the absolute height of the control in pixels.
img.GetAbsWidth
Get the absolute width of the control in pixels.
img.GetHeight
Get the height of the control as screen height relative float or in pixels with the px option.
img.GetLeft
Get the distance from the control to the left parent border as width relative float or in pixels with the px option.
img.GetName
Returns the name set via SetName.
img.GetParent
Returns the parent control object where the object was added to - commonly a layout.
img.GetPixelColor
Returns the [r,g,b] values from a pixel on the image.
img.GetPixelData
Returns the raw, png or jpg image data encoded as base64.
img.GetPosition
Returns data about the position and size of the control.
If the screen option is given the position on the screen will be returned. Otherwise relative to the parent control.
The px options turns the relative values into pixels.
img.GetTop
Get the distance from the control to the upper parent border as height relative float or in pixels with the px option.
img.GetType
Returns the control class name.
img.GetVisibility
Returns the current visibility state of the control. The Values are:
Show: visible
Hide: invisible but still consuming space
Gone: invisible and not consuming space
img.GetWidth
Get the width of the control as screen width relative float or in pixels with the px option.
img.Gone
Hides the control without consuming any more layout space as if it were never there.
img.Hide
Hide the control but keep the layout space free.
img.IsEnabled
Returns whether the control is currently useable by the user.
img.IsOverlap
Returns whether the control overlaps with another by a given distance.
img.IsVisible
Returns whether the control is currently visible to the user, ignoring overlaying controls.
img.MeasureText
Measure width and height of a given text with the current image settings.
img.Method
Allows access to other functions defined on the object in Java via reflection.

Note: This function is a premium feature. Please consider subscribing to Premium to use this feature and support DroidScript in its further development.
img.Move
Moves the content of the image to the specified position.
img.Reset
Resets all transformations.
img.Rotate
Rotates the content.
img.Save
Saves the image to a file on the local filesystem.
img.Scale
Scales the content by the given factors.
img.SetAlpha
Change the image alpha to a value between 0 and 255, where 0 is full transparent.
img.SetAutoUpdate
En/disable updating the view after every drawing or transformation method.
img.SetBackAlpha
Set the transparency of the background by an alpha value between 0 (no transparency) and 0.99 (full transparent) or 1 (no transparency) and 256 (full transparent)
img.SetBackColor
Changes the background color of the control.
img.SetBackGradient
Define the background color of the control with a gradient. The default gradient direction is from top to bottom, but you can change it from left to right and the reversed versions of course.
img.SetBackGradientRadial
Define a radial color gradient for the background of control.
img.SetBackground
Changes the background to an image which can be repeated using the repeat option.
An image which is often used with that option is '/res/drawable/pattern_carbon' - try it out!
img.SetColor
Fills the image with a specific color.
img.SetColorFilter
Adjust the visual color effect with a color and a given BlendMode. More information about BlendMode can be found in the Android Developer page.
img.SetEnabled
En/Disable the control physically and visually so that the user can/can not access the control. Events like OnTouch will still be fired.
img.SetFontFile
Change the font style by defining a font file.
img.SetImage
Set the content to an image control or specify a path to an image which will then be loaded.
img.SetLineWidth
Set the stroke width to a number in pixels.
img.SetMargins
Define a distance to other controls on each side of the control.
img.SetMaxRate
Set a minimum timeout between two touch 'move' actions fired.
img.SetName
Change the name of the image.
img.SetOnLoad
Define a callback function which is called when the image has loaded in “async” mode.
img.SetOnLongTouch
Define a callback function which is called when the object has been long pressed.
img.SetOnTouch
Define a callback function that is called when the user touches the control. In addition, an event object is passed to the callback function to obtain information about the touch type, the touch position(s), the amount of touches and the control that was touched.
img.SetOnTouchDown
Define a callback function which is called when the user started toching the control.
img.SetOnTouchMove
Define a callback function which is called when the user drags a finger over the screen.
img.SetOnTouchUp
Define a callback function which is called when the users finger leaves the screen.
img.SetPadding
Define distances that elements within the control are to maintain from the control borders.
img.SetPaintColor
Change the current paint color for drawing methods.
img.SetPaintStyle
Change the current paint style for drawing methods.
img.SetPixelData
Set the image to base64 encoded pixel data.
img.SetPixelMode
En-/Disable pixel mode for the image so that all drawing methods use either control relative or pixel values.
img.SetPosition
Defines the position and size for the control if the parent is an absolute layout.
img.SetScale
Scales the control along with its contents by the factors passed to the function.
img.SetSize
Change the size of the control in either screen relative values or in pixels if the px option was given.
img.SetTextSize
Change the size of drawn text.
img.SetTouchable
En/Disables touch events to be fired on the control. Other events like OnChange will still be fired.
img.SetVisibility
Change the visibility of the control to one of the available modes:
Show: visible
Hide: invisible but still consuming space
Gone: invisible and not consuming space
img.Show
Set the visibility of the control to “Show”.
img.Skew
Skews the content.
img.Transform
Transform the content with a 2d transformation matrix.
img.Tween
Performs an animation on the control.
The target object is for the position, size and rotation that the control has at the end of the animation.

The type specifies the behavior and the speed of the animation. Separated by a dot, you must also specify whether you want to apply this behavior to the beginning (In), end (Out), or to both (InOut) times of the animation.

With the amount of repeats you can control how many times you want to play the animation.

If you have jojo activated, the animation will alternate between forward and backward playback, so that if the repetition value is odd, the control will be at the start position again at the end of the animation.

Finally the callback function will be called after the animation has finished. Well, it's about time!
img.Update
Update the view in disabled AutoUpdate mode.