0

您好我正在尝试将图像加载到自定义类中,该类当前使用内部资源图像的 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。但是我想使用从 mediastore 带来的 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);
                    }

不幸的是它不工作。

4

1 回答 1

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)

希望能帮助到你...

于 2013-05-08T12:20:33.750 回答