我正在爲我的android課程製作一個meme生成器應用程序。我已經獲得了一個API來生成100個流行的模因,當點擊它時,它會將您帶到EditMemeActivity,您可以在其中輸入上下文。然後,有一個Create Meme按鈕,它將帶您進入MemeActivity,您最終可以保存/與朋友分享。目前,當單擊創建meme按鈕時,該meme圖片將轉換爲位圖,並在下一頁顯示正常。我希望能夠將用戶在圖像上輸入的上部和下部文本保存爲位圖。由於某些模板圖像的大小不同,因此我將它們周圍的黑色背景設置爲約400X300像素,所以我希望能夠捕獲整個圖像視圖並將輸入的文本置入。以下是我的兩個活動的代碼:Android:如何將ImageView轉換爲位圖並傳遞給另一個活動?
public class EditMemeActivity extends AppCompatActivity {
@Bind(R.id.editMemeImage) ImageView mEditMemeImage;
@Bind(R.id.editUpperText) EditText mEditUpperText;
@Bind(R.id.editLowerText) EditText mEditLowerText;
@Bind(R.id.saveMeme) Button mSaveMeme;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String image = intent.getStringExtra("image");
final String upper = mEditUpperText.getText().toString();
final String lower = mEditLowerText.getText().toString();
final Bitmap memeBitmap = getBitmapFromURL(image);
Picasso.with(EditMemeActivity.this).load(image).into(mEditMemeImage);
mSaveMeme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(EditMemeActivity.this, MemeActivity.class);
intent.putExtra("bitmap", memeBitmap);
intent.putExtra("upper", upper);
intent.putExtra("lower", lower);
startActivity(intent);
}
});
}
public static Bitmap getBitmapFromURL(String image) {
try {
URL url = new URL(image);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
public class MemeActivity extends AppCompatActivity {
@Bind(R.id.memeImageView) ImageView mMemeImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String upperText = intent.getStringExtra("upper");
String lowerText = intent.getStringExtra("lower");
byte[] byteArray = getIntent().getByteArrayExtra("bitmap");
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mMemeImageView.setImageBitmap(bitmap);
}
}