diff --git a/packages/taro-components/src/components/image/index.js b/packages/taro-components/src/components/image/index.js index 559e366cdfb6..51ebbdfaa1a7 100644 --- a/packages/taro-components/src/components/image/index.js +++ b/packages/taro-components/src/components/image/index.js @@ -9,7 +9,8 @@ class Image extends Nerv.Component { constructor () { super(...arguments) this.state = { - isLoaded: false + isLoaded: false, + aspectFillMode: 'width' } this.imageOnLoad = this.imageOnLoad.bind(this) } @@ -43,6 +44,11 @@ class Image extends Nerv.Component { height: this.imgRef.height } }) + if (this.imgRef.naturalWidth > this.imgRef.naturalHeight) { + this.setState({ aspectFillMode: 'width' }) + } else { + this.setState({ aspectFillMode: 'height' }) + } onLoad && onLoad(e) } @@ -56,6 +62,7 @@ class Image extends Nerv.Component { lazyLoad, ...reset } = this.props + const { aspectFillMode } = this.state const cls = classNames( 'taro-img', { @@ -65,7 +72,10 @@ class Image extends Nerv.Component { ) const imgCls = classNames( 'taro-img__mode-' + - (mode || 'scaleToFill').toLowerCase().replace(/\s/g, '') + (mode || 'scaleToFill').toLowerCase().replace(/\s/g, ''), + { + [`taro-img__mode-aspectfill--${aspectFillMode}`]: mode === 'aspectFill' + } ) return ( diff --git a/packages/taro-components/src/components/image/style/index.scss b/packages/taro-components/src/components/image/style/index.scss index 0d64e943571e..f8b72794839e 100644 --- a/packages/taro-components/src/components/image/style/index.scss +++ b/packages/taro-components/src/components/image/style/index.scss @@ -21,8 +21,18 @@ img[src=""] { max-height: 100%; } &-aspectfill { - min-width: 100%; - height: 100%; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + &--width { + min-width: 100%; + height: 100%; + } + &--height { + width: 100%; + min-height: 100%; + } } &-widthfix { width: 100%;