android - How can I save an XML layout resource to an image? -
i want able save 1000x1000 .png image layout xml created. i've found samples online of people saving displayed views .png file, can't find sample code creating image layout that's not being displayed. could save what's being shown on screen, because image being created similar, don't want layout/resolution determined device size/layout/orientation; want image saved same on every device. i'm new android, , i've spent several hours trying figure out how this, couldn't find anything. xml code saveable_image_layout.xml:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="1000px" android:layout_height="1000px" android:id="@+id/sil_main"> <framelayout android:layout_width="match_parent" android:layout_height="500px"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/sil_quote_text" android:layout_gravity="start|bottom" android:textsize="30sp" android:fontfamily="sans-serif-condensed" android:text="sample text 1"/> </framelayout> <framelayout android:layout_width="match_parent" android:layout_height="500px"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/sil_person_text" android:layout_gravity="end" android:textsize="24sp" android:fontfamily="sans-serif-thin" android:text="sample text 2"/> </framelayout> </linearlayout>
and try save image this:
layoutinflater inflater = layoutinflater.from(getapplicationcontext()); view view = inflater.inflate(r.layout.saveable_image_layout, null); linearlayout layout = view.findviewbyid(r.id.sil_main); bitmap bitmap = layout.getdrawingcache(); canvas canvas = new canvas(bitmap); layout.draw(canvas); try { file file = new file(environment.getexternalstoragedirectory(), "img-" + system.currenttimemillis() + ".png"); log.v(log_tag, file.tostring()); fileoutputstream out = new fileoutputstream(file); bitmap.compress(bitmap.compressformat.png, 100, out); out.flush(); out.close(); } catch (ioexception e) { e.printstacktrace(); }
but end error,
java.lang.nullpointerexception: attempt invoke virtual method 'boolean android.graphics.bitmap.ismutable()' on null object reference
so i'm guessing inflater.inflate() call returning null, i'm not sure why. going wrong? there better way should doing this?
i think have not enabled drawing cache try add following code before call getdrawingcache()
layout.setdrawingcacheenabled(true); // important code :) // without view have dimension of 0,0 , bitmap null layout.measure(measurespec.makemeasurespec(0, measurespec.unspecified), measurespec.makemeasurespec(0, measurespec.unspecified)); layout.layout(0, 0, layout.getmeasuredwidth(), layout.getmeasuredheight()); layout.builddrawingcache(true);
hope helps.
Comments
Post a Comment