I'm using the custom view TouchImageView
. However, when I set the bitmap it doesn't show the image unless I do a pinch gesture on it.
public class PhotoOverlayActivity extends AppCompatActivity {
public static final String CURRENT_MESSAGE_KEY = "message";
private static final int IMAGE_REQUEST_CODE = 0;
String currentMessage;
private Bitmap bitmap;
private TouchImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_overlay);
setupToolbar();
setupImageView();
currentMessage = getIntent().getStringExtra(CURRENT_MESSAGE_KEY);
chooseImage();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setTitle("");
}
}
private void setupImageView() {
mImageView = findViewById(R.id.imageView);
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, IMAGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
I finally found the solution buried here, so I am posting my answer below.
After calling
mImageView.setImageBitmap(yourBitmap);
do
mImageView.setZoom(1f);
Another option would be to modify the source code to do the same thing since the TouchImageView
class is contained in your project anyway.
Thanks to this post for the idea.