Skip to content

Instantly share code, notes, and snippets.

@coodoo
Last active December 5, 2020 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coodoo/c1f3fb6a0c4e1f97d18ba3f1d4c86547 to your computer and use it in GitHub Desktop.
Save coodoo/c1f3fb6a0c4e1f97d18ba3f1d4c86547 to your computer and use it in GitHub Desktop.
import {
PixelRatio,
Dimensions,
useWindowDimensions
} from 'react-native'
const to = n => Number(n.toFixed(2))
const { width, height } = Dimensions.get('window')
// 將短的那邊視為 width
const [ shortDimension, longDimension ] = width < height ? [width, height] : [height, width]
/*
- 350*680 是一般 5" 手機常見的 size (iphone 6/7/8 為 375*667, i12 max pro = 414*896 )
- 可將 base w/h 改成與設計稿一樣,就能直接用它的元素值,否則就會靠肉眼微調數字以逼近設計稿
- useWindowDimensions() 比 Dimensions 好的地方在於裝置旋轉後會提供新值
- 用法
import s from './sizer'
<View style={{
width: s.scaleW(130),
height: s.scaleH(650)
}}
/>
*/
class Sizer {
BASE_W = 350
BASE_H = 680
scaleW(val) {
return to( val/this.BASE_W * shortDimension )
}
scaleH(val) {
return to( val/this.BASE_H * longDimension )
}
// 這支可減緩等比縮放的量,在密度越高裝置可能越適合
scaleW2(val, factor = 0.5) {
return to( val + ( scaleW(val) - val ) * factor )
}
scaleH2(val, factor = 0.5) {
return to( val + ( scaleH(val) - val ) * factor )
}
// 設定新 screen size,後續 scale() 就會據此計算比例,目地是方便在 iphone 與 ipad 設計稿間切換
setSize(w=350, h=680) {
this.BASE_W = w
this.BASE_H = h
console.log( '新 screen size=', this.BASE_W, this.BASE_H )
}
getSize = function() {
return { width: this.BASE_W, height: this.BASE_H }
}
}
export default new Sizer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment