Back

CreateImage

Hello World

Image controls can be used to display images such like png, jpg or gif.
Just pass the file path and your'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
GetHeight( options ) → number
GetLeft( options ) → number
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 }
GetTop( options ) → number
GetType() → string: “Image”
GetVisibility() → string: “Show” or “Hide” or “Gone”
GetWidth( options ) → number
Gone()
Hide()
IsEnabled() → boolean
IsOverlap( obj, depth ) → boolean
IsVisible() → boolean
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: path to file or folder ( “/absolute/...” or “relative/...” )
string: comma “,” separated: “fix”, “alias”, px, Button, “ScaleCenter”, async, “FontAwesome”, “Resize”, “TouchThrough”, Icon, “wallpaper”, NoPlay
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, w, sw, sh, rot }
app object: Image
list: [a, b, c, d, tx, ty]
list: [ data ]
list: boolean,char,byte,short,int,long,float,double,String,CharSequence,...
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.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 his 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.