使用 resizeMode = 包含时的图像对齐 [英] Image Alignment when using resizeMode = contain

查看:40
本文介绍了使用 resizeMode = 包含时的图像对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Native 的 Image 标签来显示具有可变宽度和高度的图像.我已将图像设置为 100x50 并设置 resizeMode = contains,这几乎完美地工作,但是如果图像调整大小,它会在垂直和水平方向完全居中.这种行为可以改变吗?样机截图:

I'm using React Native's Image tag to display an image with a variable width and height. I have set the Image to 100x50 and set the resizeMode = contain which works almost perfectly, however if the image is resized, it's coming out completely centered vertically and horizontally. Can this behavior be altered? Mockup screenshot :

红色框表示图像元素设置为 100x50.笔记本电脑图片代表可变宽度/高度图片.您会注意到这种行为是将所有内容垂直或水平地推向中心.

The red box indicates the Image element set at 100x50. The laptop pic represents the variable width/height picture. You'll notice that the behavior is pushing everything centered either vertically or horizontally.

在第二个示例中,我希望将占据 100% 高度和大约一半宽度的图片推到左对齐.这可能吗?

In the second example, I would like the picture that takes up 100% of the height and roughly half the width to be pushed to be left aligned. Is this possible?

谢谢!

推荐答案

All - 为了将来可能节省一些时间,这是我想出的一种快速而肮脏的方法来解决这个问题:

All - to possibly save some time in the future, this is a quick and dirty method I came up with to resolve this :

logoSize(width, height) {
  var maxWidth = 110;
  var maxHeight = 30;

  if (width >= height) {
    var ratio = maxWidth / width;
    var h = Math.ceil(ratio * height);

    if (h > maxHeight) {
      // Too tall, resize
      var ratio = maxHeight / height;
      var w = Math.ceil(ratio * width);
      var ret = {
        'width': w,
        'height': maxHeight
      };
    } else {
      var ret = {
        'width': maxWidth,
        'height': h
      };
    }

  } else {
    var ratio = maxHeight / height;
    var w = Math.ceil(ratio * width);

    if (w > maxWidth) {
      var ratio = maxWidth / width;
      var h = Math.ceil(ratio * height);
      var ret = {
        'width': maxWidth,
        'height': h
      };
    } else {
      var ret = {
        'width': w,
        'height': maxHeight
      };
    }
  }

  return ret;
}

这将获取图像的宽度和高度,运行一些比率计算,并根据顶部的 maxWidth 和 maxHeight 变量吐出一组尺寸.然后,您可以采用上述方法为您提供的尺寸并将其应用于 Image 元素,例如:

This will take a width and height of an image, run through some ratio calculations, and spit out a set of dimensions based on maxWidth and maxHeight vars at the top. You can then take the dimensions the method above gives you and apply it to an Image element e.g. :

var dims = logoSize(244,127);
<Image style={[styles.logo, {width:dims.width, height:dims.height}]} source={{uri:'/path/to/image.png}} />

由于计算四舍五入,您可能需要将 resizeMode:'contain' 应用到样式表中的 style.logo.

Since the calculations rounds, you may need to apply the resizeMode:'contain' to the styles.logo in your Stylesheet.

希望这可以为某人节省一些时间.

Hope this saves someone some time.

这篇关于使用 resizeMode = 包含时的图像对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆