具有任意宽高比的android Gallery

标签 android image gallery

我希望有一个 android 画廊,可以容纳不同宽高比的图像。我想要的是画廊中图像的 CENTER_CROP。然而,当我将图像缩放类型设置为此时,图像会超出图库图像边界。

当然,FIT_XY 会导致图像被压扁/变平。 CENTER 会在图库图像边框内产生水平或垂直的黑色空间。

有什么想法可以实现吗?我能找到的每个示例都使用 FIT_XY 和固定大小的图像。我想我可以自己裁剪图像,但我不想这样做。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView iv = (ImageView) convertView;
    if (iv == null) {
        iv = new ImageView(context);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);
        iv.setBackgroundResource(galleryItemBackground);
        iv.setLayoutParams(new Gallery.LayoutParams(200, 200));
    }

    InputStream is;
    try {
        is = getInputStream(position);
    } catch (IOException ioe) {
        // TODO?
        throw new RuntimeException(ioe);
    }
    Bitmap bm = BitmapFactory.decodeStream(is);
    iv.setImageBitmap(bm);



    /*
     * if (bitmaps[position] != null) { bitmaps[position].recycle();
     * bitmaps[position] = null; } bitmaps[position] = bm;
     */

    return iv;
}

最佳答案

我遇到了和你一样的问题,在查看 ScaleType 文档时我发现它可以使用 ScaleType.MATRIX 来完成,例如:

    int w = 1000;
    int h = 1000;

    Paint p = new Paint();
    p.setShader(new LinearGradient(0, 0, w, h, Color.BLACK, Color.RED, Shader.TileMode.CLAMP));

    Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas g = new Canvas(bmp);     
    g.drawRect(new Rect(0, 0, w, h), p);

    ImageView i3 = new ImageView(context);
    i3.setImageBitmap(bmp);
    i3.setScaleType(ScaleType.MATRIX);

    int viewWidth = 300;
    int viewHeight = 300;

    Matrix matrix = new Matrix();
    matrix.postScale(bmp.getWidth() / viewWidth, bmp.getHeight() / viewHeight, bmp.getWidth() / 2, bmp.getHeight() / 2);
    i3.setImageMatrix(matrix);

    LayoutParams lp2 = new LayoutParams(viewWidth, viewHeight);
    lp2.leftMargin = 100;
    lp2.topMargin = 400;
    lp2.gravity = 0;

    this.addView(i3, lp2);

虽然这个解决方案让事情变得有点复杂。如果您想滚动和缩放 ImageView,您还需要使用矩阵缩放。所以我很想知道任何可能的替代方案。

关于具有任意宽高比的android Gallery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5706980/

相关文章:

javascript - jQuery 媒体浏览器

android - 如何在我的代码中动态清空或清除堆内存

java - 如何向 EditText 添加过滤器?

android - 在 Activity 之外显示对话

java - 需要帮助将数组 imageicon 解析为 JButton

algorithm - 有没有 "special"人脸案例的图片压缩算法?

c# - 获取 ViewPager fragment 中的当前索引

Android:如何在连续移动时找到使用 GPS 覆盖的总距离?

css - 可以使用 css 或 bootstrap 创建具有不同大小图像的图像网格吗?

excel - PowerApps,使用图库显示集合 + 附加变量