
我正在尝试使用SD卡中的图像并将其设置为相对布局的背景.我尝试了其他在这里和其他地方找到的解决方案,但它们似乎并不适合我.这是我的代码.我已经评论了其他方法,我尝试过但没有工作.对我来说唯一有用的是使用setBackgroudnResource并使用应用程序中的资源,但这只是为了确保mRoot设置正确.当我尝试所有其他方式时,它只是没有设置任何东西.任何人都知道我做错了什么,或者是否有更好的方法来做到这一点?
//one way i tired...//String extDir = Environment.getExternalStorageDirectory().toString();//Drawable d = Drawable.createFromPath(extDir + "/pic.png");//mRoot.setBackgroundDrawable(d);//another way trIEd..//Drawable d = Drawable.createFromPath("/sdcard/pic.png");//mRoot.setBackgroundDrawable(d);//last way i trIEd...mRoot.setBackgroundDrawable(Drawable.createFromPath(new file(Environment.getExternalStorageDirectory(), "pic.png").getabsolutePath()));//worked, only to verify mRoot was setup correctly and it Could be changed//mRoot.setBackgroundResource(R.drawable.bkg);解决方法:
您不从SD卡加载drawable而是加载位图.这是一种用减少的采样(质量)加载它的方法,因此如果图像太大,程序不会抱怨.然后我想你需要处理这个位图,即裁剪它并调整背景大小.
// Read bitmap from Uri public Bitmap readBitmap(Uri selectedImage) { Bitmap bm = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; //reduce quality AssetfileDescriptor fileDescriptor =null; try { fileDescriptor = this.getContentResolver().openAssetfileDescriptor(selectedImage,"r"); } catch (fileNotFoundException e) { e.printstacktrace(); } finally{ try { bm = BitmapFactory.decodefileDescriptor(fileDescriptor.getfileDescriptor(), null, options); fileDescriptor.close(); } catch (IOException e) { e.printstacktrace(); } } return bm; }这里的Uri可以从画廊选择器活动中提供.
然后可以将图像保存到应用程序资源中并加载到imageVIEw中
private voID saveBackground(Bitmap Background) { String strBackgroundfilename = "background_custom.jpg"; try { Background.compress(CompressFormat.JPEG, 80, openfileOutput(strBackgroundfilename, MODE_PRIVATE)); } catch (Exception e) { Log.e(DEBUG_TAG, "Background compression and save Failed.", e); } Uri imageUriToSaveCameraimageto = Uri.fromfile(new file(BackgroundSettings.this.getfilesDir(), strBackgroundfilename)); // Load this image Bitmap bitmAPImage = BitmapFactory.decodefile(imageUriToSaveCameraimageto.getPath()); Drawable bgrImage = new BitmapDrawable(bitmAPImage); //show it in a vIEw ImageVIEw backgroundVIEw = (ImageVIEw) findVIEwByID(R.ID.BackgroundImageVIEw); backgroundVIEw.setimageURI(null); backgroundVIEw.setimageDrawable(bgrImage); } 总结 以上是内存溢出为你收集整理的从sd卡创建一个drawable,在android中设置为背景全部内容,希望文章能够帮你解决从sd卡创建一个drawable,在android中设置为背景所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)