hunterp
hunterp

Reputation: 15976

How to render a tricky ass NinePatch?

This is thebasic idea, but the image is ugly and pixelated. WHY???


public class Main extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView iv = (ImageView) findViewById(R.id.iv);
    Bitmap bmap = BitmapFactory.decodeResource(getResources(), R.drawable.btn_default_normal);
    NinePatchDrawable npd = new NinePatchDrawable(bmap, bmap.getNinePatchChunk(), new Rect(0,0,512,512), "name");
    npd.mutate();
    npd.setBounds(new Rect(0,0,512,512));
    npd.invalidateSelf();
    Bitmap bp = Bitmap.createBitmap(512,512, Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bp);
    npd.draw(canvas);
    FileOutputStream ofo=null;
    try {
      ofo = openFileOutput("image", MODE_WORLD_READABLE);
    } catch (IOException e) {
      e.printStackTrace();
    }
    bp.compress(Bitmap.CompressFormat.PNG, 100, ofo);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.putExtra(Intent.EXTRA_STREAM, getFileStreamPath("image").toURI());
    intent.setType("image/png");
    //startActivity(intent);
    iv.setImageDrawable(new BitmapDrawable(bp));
  }
}

Upvotes: 0

Views: 496

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134664

You're making it infinitely more complicated than it needs to be. Just set your view in the XML like so:

<TextView
        android:background="@android:drawable/btn_default_small"        
        android:layout_width="512px"
        android:layout_height="wrap_content"
        android:text="NinePatch View"
        />

Just using TextView as an example. The same will work for an ImageView, a View, pretty much any widget. The important thing to remember is to use the background attribute instead of the src attribute for an ImageView. The src attribute will stretch the image as is, it won't respect the NinePatch data.

If you're set on doing it in code, just use:

iv.setBackgroundResource(R.drawable.btn_default_small)

As a side note, what device are you displaying it on? Most mobile phones only have up to 480 pixels for the width.

Upvotes: 1

Related Questions