Skip to content

Instantly share code, notes, and snippets.

@bugabinga
Created September 6, 2013 09:15
Show Gist options
  • Save bugabinga/6461451 to your computer and use it in GitHub Desktop.
Save bugabinga/6461451 to your computer and use it in GitHub Desktop.
Simple mgwt square icon. The default size is dependent on current font size. This is because icons usually decorate text in some form.
/**
*
*/
package com.bugabinga.widgets;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.googlecode.mgwt.ui.client.widget.Button;
import com.googlecode.mgwt.ui.client.widget.touch.TouchWidget;
/**
* A small decorative widget, a square containing an iconic image. Usually used to decorate other elements
* like {@link Button}.
*
* @author okr
*/
public class Icon extends TouchWidget
{
private final Element icon = DOM.createDiv();
/**
* <p>
* Constructs an Icon. Default size is 1.5em, roughly 24x24px depending on target device.
* </p>
*/
public Icon()
{
setElement( icon );
// streches the image to the box' aspect ratio
getElement().getStyle().setProperty( "backgroundRepeat", "no-repeat" );
// resizes the image to whatever the area of the box is
getElement().getStyle().setProperty( "backgroundSize", "100% 100%" );
// FIXME(okr):could be refactored out into css style if this would be part of MGWT
setDefaultSize();
}
/**
* Constructs an icon from image resource
*
* @param img image data url
*/
public Icon( final ImageResource img )
{
this();
setTexture( img.getSafeUri().asString() );
}
/**
* Constructs an Icon with given data.
*
* @param dataResource data
*/
public Icon( final DataResource dataResource )
{
this();
setTexture( dataResource.getSafeUri().asString() );
}
/**
* @param base64 data string
* @param imgType image type
*/
public Icon( final String base64, final String imgType )
{
this();
if ( !base64.isEmpty() ) setTexture( "data:image/" + imgType + ";base64," + base64 );
else setSize( 0, Unit.PX );
}
/**
* Sets the size of the square icon box to its default size of 1em.
*/
public void setDefaultSize()
{
setSize( 1, Unit.EM );
}
/**
* Sets the size of the icon. The default size is 1em, approximately 16x16px depending on the target device.
*
* @param value value
* @param unit unit
*/
public void setSize( final double value, final Unit unit )
{
getElement().getStyle().setHeight( value, unit );
getElement().getStyle().setWidth( value, unit );
}
/**
* @param dataUrl icon texture
*/
public void setTexture( final String dataUrl )
{
getElement().getStyle().setBackgroundImage( "url('" + dataUrl + "')" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment