canvas - Android draw image when clicking button -
basically, have button when clicked, image appear in random coordinate..
here's code :
public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); //mdrawable = getresources().getdrawable(r.drawable.icon); log.i("info", "resource got !!"); mbitmap = bitmapfactory.decoderesource(getresources(), r.drawable.icon); mcanvas = new canvas(); invoker = (button) findviewbyid (r.id.invoke); invoker.setonclicklistener(this); } public void onclick(view v) { if (v.getid() == r.id.invoke) { log.i("info", "button clicked !!"); display d = getwindowmanager().getdefaultdisplay(); log.i("info", "returning window info !!"); // todo auto-generated method stub xpos = randint.nextint(d.getwidth()); ypos = randint.nextint(d.getheight() - invoker.getheight())+ invoker.getheight(); log.i("info", "coord got !!, xpos = "+xpos+", ypos = "+ypos); mcanvas.drawbitmap(mbitmap, ypos, xpos, null); log.i ("info", "image drawn @ ("+xpos+", "+ypos+")"); } }
here's problem. whenever clicked button, image drawn, seen....there's no image drawn on screen whenever press button...
pls point out mistake ?? thx
note : no error in logcat
just because created canvas not mean it's associated on display, canvas virtual drawing surface way have done it.
there few ways this, easiest create custom view, override ondraw method, , display bitmap in there.
add custom view layout fill_parent height , width
when button clicked set x/y image , invalidate view
update
ok here custom view becomes drawing surface image, insert main layout, make full screen if (assuming using relativelayout can add other views,buttons,etc anywhere want) a
extend putting drawing code appropriate if/block. custom class using findviewbyid button.
now when want draw image based on button click call methods on custom view instance. thats 1 trivial way anyway.
you extend layout class (whatever using in main) , same thing without adding child view.
public class myview extends view { private boolean imageshow = false; private int x = 0; private int y = 0; public myview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); } public myview(context context) { this(context,null,0); } public myview(context context, attributeset attrs) { this(context, attrs,0); } public void drawimagerandom() { imageshow = true; invalidate(); } public void hideimage() { imageshow = false; invalidate(); } @override public void ondraw(canvas canvas) { super.ondraw(canvas); if (imageshow) { // drawing code in here } } }
Comments
Post a Comment