嗨我正在尝试将图像加载到自定义类中,此类当前使用内部资源图像的int ID,但我希望该选项也可以使用图库或照片图像。
这是使用内部资源图像创建视图的当前代码段。
public TouchExampleView(Context context, AttributeSet attrs, int defStyle, int pic) {
super(context, attrs, defStyle);
Log.i(TAG, "pic before: "+pic);
if (pic ==0) pic = getResources().getIdentifier("ic_launcher" , "drawable", "com.example.testimage");
Log.i(TAG, "pic afgter: "+pic);
//mIcon = context.getResources().getDrawable(R.drawable.testpic);
mIcon = context.getResources().getDrawable(pic);
mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());
mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback());
}
您可以看到上面的代码正在使用“pic”来允许内部资源ID通过。但是我想使用媒体商店带来的ID,如下所示:
final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
TouchExampleView view = new TouchExampleView(this, null, 0, id);
}
不幸的是它不起作用。
答案 0 :(得分:1)
为什么不用constructor
drawable
像
public TouchExampleView(Context context, AttributeSet attrs, int defStyle, Drawable pic) {
super(context, attrs, defStyle);
Log.i(TAG, "pic before: "+pic);
if (pic == null) pic = getResources().getDrawable(R.drawable.ic_launcher);
Log.i(TAG, "pic afgter: "+pic);
//mIcon = context.getResources().getDrawable(R.drawable.testpic);
mIcon = pic;
mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());
mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback());
}
并像这样得到抽象
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.TITLE };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(filePath);
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Drawable d = new BitmapDrawable(getResources(),bitmap);
现在使用TouchExampleView
Drawable
的新对象
new TouchExampleView(context, attrs, defStyle, d)
希望它有所帮助...