Is there a way to scale a View in react-native? - javascript

I have a View in react-native with a few components. While everything shows up correctly on the iPhone 6 and 5, when viewing it on an iPhone 4s, the bottom of one of the components is slightly cut off.
I see there are ways to scale base64 icons. Is there any way to scale an entire container View to be uniformly smaller or larger?

Your question can be break down into two parts:
1, To scale width, height, paddings and margins. These can be easily achieve by using % and aspectRatio.
2, To scale Text, you might want to consider using Extended StyleSheet, which allows you to use rem.
You can simply following tutorial "7 Tips to Develop React Native UIs For All Screen Sizes" for how to use the above tips.
Additionally, check out Extended StyleSheet Scaling, which allows to use $scale variable to scale base on conditions.

Does something like this help you ?
YourStyleSheet.js
import {StyleSheet} from 'react-native';
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');
export function create(styles: Object): {[name: string]: number} {
const platformStyles = {};
Object.keys(styles).forEach((name) => {
let {sm,md,lg, ...style} = {...styles[name]};
// iphone 4s and older
if(sm && width < 375){
style = {...style, ...sm};
}
// iphone 5,5s
if(md && width >= 375 && width <414){
style = {...style, ...md};
}
// iphone 6 and bigger
if(lg && width >= 414){
style = {...style, ...lg};
}
platformStyles[name] = style;
});
return StyleSheet.create(platformStyles);
}
Then in your style you can specify the size of the component on different screen sizes like this
import YourStyleSheet from './path/YourStyleShett'
const styles = YourStyleSheet.create({
component:{
sm:{fontSize: 20,},
md:{fontSize: 30,},
lg:{fontSize: 30,},
textAlign: 'center',
marginBottom: 10,
fontWeight:'bold',
color:colors.white,
}
});

Related

Unexpected border pattern in a grid with rectangles in p5.js

I am trying to generate a square grid like pattern in p5js that covers as much of the browser window as possible.I am using p5js in instance mode as I using this with react and I am using chrome in Win10.
Here is my code:-
var size = 15;
var height = window.innerHeight;
var width = window.innerWidth;
Sketch = (p) => {
p.setup = () => {
p.createCanvas(width,height)
p.frameRate(60);
p.noLoop();
}
p.draw = () => {
p.background(250);
p.stroke(0);
p.noFill();
for(let i =0;i*size +size <width;i++) {
for(let j=0;j*size +size<height;j++) {
p.rect(i*size,j*size,size,size);
}
}
}
p.mouseDragged = (e) => {
p.stroke(0);
let x = Math.floor(e.clientY/size);
let y = Math.floor(e.clientX/size);
p.fill(220);
p.rect(y*size,x*size,size,size);
}
}
I call p.noLoop() so it doesnt refreshes everytime and I also have a button that calls p.redraw() to change everything to default. Here is the grid and behaviour I get:
The borders of grids are of varying sizes, first they decrease then increase then decrease and so on. Also, the area around which I drag my mouse has even more weird borders(This gets resolved when I click somewhere else so is this a GPU Aliasing rendering issue?). How do I create grid with same borders throughout my screen?
Edit: When I render even a single box, it has issues. The left and upper border are fine. However the right and down borders have an extra pixel of grayish borders which seems to be the problem. How do I fix this?
Also, How does strokeWeight and rect work in p5js? If I do strokeWeight(10) and rect(3,2,50,50), does that create a 50 by 50 rectangle with 10 pixels borders all around or the borders are included in the rectangle size?

How can I prevent both vertical and horizontal stretching of contained text while resizing text-based objects in Fabric.js?

I want to be able to scale text-based objects (for example with classes and subclasses of IText, Textbox) without stretching the text inside of the object. The interaction of scaling and moving is on user-side (UI), not programmatically (I am working on a drawing editor).
The behaviour I am looking for is similar to the one in the sticky notes apps: You can scale the paper but this action does not scale your text too.
I have already checked this, but this is only for horizontal prevention: Fabric.js How to resize IText horizontally without stretching the text
This is neither what I want/mean: Fabric.js : How to set a custom size to Text or IText?
I know that a scaling factor different than 1 implies the stretching of the inner text, and that by changing the width and height I can resize the object while keeping the text unscaled, so I tried updating these during scaling using events listeners.
I tried many combinations of the IText,Textbox with some scaling events, like this one:
fbtext.on('scaling', function() {
this.set({
width : this.width * this.scaleX,
height: this.height * this.scaleY,
scaleX: 1,
scaleY: 1,
});
});
I also tried this with Textbox:
fbtext.on('scaling', function() {
this.set({
height: this.height * this.scaleY,
});
});
But nothing worked so far. I am out of ideas.
var canvas = new fabric.Canvas('mycanvas');
let textbox = new fabric.Textbox("Sample text", {
left: 100,
top: 100
});
let lastHeight;
const updateTextSize = () => {
const controlPoint = textbox.__corner;
//mr and ml are the only controlPoints that dont modify textbox height
if( controlPoint && controlPoint != "mr" && controlPoint != "ml"){
lastHeight = textbox.height * textbox.scaleY;
}
textbox.set({
height: lastHeight || textbox.height,
scaleY:1
});
canvas.renderAll();
};
textbox.on('scaling', updateTextSize );
textbox.on('editing:entered', updateTextSize);
canvas.on('text:changed', updateTextSize);
canvas.add(textbox);
canvas {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.3.2/fabric.min.js"></script>
<canvas id="mycanvas" width="400" height="400"></canvas>
Here is a code sample that will let you modify the "sticky note size" without streching out the text
Thanks #Ivan, your solution is working for me, with a small glitch.
When increasing the size of the text box using corners the text is getting stretched and compressed. I haven't found the solution of this yet and have currently implemented a workaround to hide all the corner scaling points.
box.setControlsVisibility({
bl: false,
br: false,
tl: false,
tr: false
});
http://jsfiddle.net/bkgvewh6/
Just to add I am posting this as an answer and not as a comment to your answer as I don't have stack overflow reputation to do so.

How do I set the color of the notch on iPhone X in React Native

I have been testing my application on an iPhone X via iOS Simulator. I would like to know how I can recolour the black notch to the same color as my application theme.
Here's the current implementation:
How do I change the black bar to blue, matching my theme?
You can simply use SafeAreaView from react-native new version 51.
import {
...
SafeAreaView
} from 'react-native';
class Main extends React.Component {
render() {
return (
<SafeAreaView style={styles.safeArea}>
<App />
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
...,
safeArea: {
flex: 1,
backgroundColor: '#FF5236'
}
})
See: How to set iOS status bar background color in React Native?
For an iPhone X, the increase StatusBarHeightIos from 20 to 30
I use react-native-device-info to detect device
import DeviceInfo from 'react-native-device-info';
// getModel: iPhone X
// getDeviceId: iPhone10,3
const ModelIphoneX = 'iPhone X';
// StatusBarHeight is where Carrier info and date display at top
// iPhone X has a cut-out in top of dispaly where sensor package is located.
// For iPhone X increase height so cut-out does not hide text
const StatusBarHeightIos = DeviceInfo.getModel() === ModelIphoneX ? 30 : 20;
const StatusBarHeight = Platform.OS === 'ios' ? StatusBarHeightIos : 0;
Screenshot: iPhone X on left
This is fixed by changing the app launch screen from image assets to a Storyboard, using XCode.

Gridstack - widget's max width bigger than grid width crashes resizing of widget

I'm using gridstack.js (v0.2.6) library for my dashboard view in web application. I tried to implement a possibility to let user change the grid width. Almost everything seems to be working, but I encountered a problem with maxWidth of widgets. Setting widget's maxWidth to bigger value than number of grid columns seems to be crashing resizing of widget. For example, when I set gridWidth = 3 and widget's maxWidth = 5, I can resize widget to max ~1.3 * column width instead of 3 columns.
I provide the most important parts of code:
HTML
<div class="grid-stack grid-stack-3">
</div>
Javascript
Initialization:
var $dashboard = $('.grid-stack');
var columnsNumber = 3;
function initGridStack() {
$dashboard[0].className = "grid-stack grid-stack-" + columnsNumber;
var options = {
cell_height: 200,
vertical_margin: 10,
animate: true,
width: columnsNumber,
draggable: {
handle: '.widget-header',
}
};
$dashboard.gridstack(options);
Adding widget:
// ...
$widget = createWidgetElement()
$dashboard.data('gridstack').addWidget($widget, x, y, width, height, autoposition, minWidth, maxWidth, minHeight, maxHeight);
Question
Has anybody had a similar problem and has any idea how can I handle this? I'll be grateful for any help.

How to auto-slide the window out from behind keyboard when TextInput has focus?

I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput> field gets focus and is positioned low in the view, the keyboard will cover up the text field.
You can see this issue in example UIExplorer's TextInputExample.js view.
Does anyone have a good solution?
2017 Answer
The KeyboardAvoidingView is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015 Answer
The correct way to do this in react-native does not require external libraries, takes advantage of native code, and includes animations.
First define a function that will handle the onFocus event for each TextInput (or any other component you would like to scroll to):
// Scroll a component into view. Just pass the component ref string.
inputFocused (refName) {
setTimeout(() => {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(this.refs[refName]),
110, //additionalOffset
true
);
}, 50);
}
Then, in your render function:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
This uses the RCTDeviceEventEmitter for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard.
You may want to play around with the additionalOffset parameter, to fit the needs of your specific UI design.
Facebook open sourced KeyboardAvoidingView in react native 0.29 to solve this problem. Documentation and usage example can be found here.
We combined some of the code form react-native-keyboard-spacer and the code from #Sherlock to create a KeyboardHandler component that can be wrapped around any View with TextInput elements. Works like a charm! :-)
/**
* Handle resizing enclosed View and scrolling to input
* Usage:
* <KeyboardHandler ref='kh' offset={50}>
* <View>
* ...
* <TextInput ref='username'
* onFocus={()=>this.refs.kh.inputFocused(this,'username')}/>
* ...
* </View>
* </KeyboardHandler>
*
* offset is optional and defaults to 34
* Any other specified props will be passed on to ScrollView
*/
'use strict';
var React=require('react-native');
var {
ScrollView,
View,
DeviceEventEmitter,
}=React;
var myprops={
offset:34,
}
var KeyboardHandler=React.createClass({
propTypes:{
offset: React.PropTypes.number,
},
getDefaultProps(){
return myprops;
},
getInitialState(){
DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
if (!frames.endCoordinates) return;
this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
this.setState({keyboardSpace:0});
});
this.scrollviewProps={
automaticallyAdjustContentInsets:true,
scrollEventThrottle:200,
};
// pass on any props we don't own to ScrollView
Object.keys(this.props).filter((n)=>{return n!='children'})
.forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]});
return {
keyboardSpace:0,
};
},
render(){
return (
<ScrollView ref='scrollView' {...this.scrollviewProps}>
{this.props.children}
<View style={{height:this.state.keyboardSpace}}></View>
</ScrollView>
);
},
inputFocused(_this,refName){
setTimeout(()=>{
let scrollResponder=this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(_this.refs[refName]),
this.props.offset, //additionalOffset
true
);
}, 50);
}
}) // KeyboardHandler
module.exports=KeyboardHandler;
First you need to install react-native-keyboardevents.
In XCode, in the project navigator, right click Libraries ➜ Add
Files to [your project's name] Go to node_modules ➜
react-native-keyboardevents and add the .xcodeproj file
In XCode, in the
project navigator, select your project. Add the lib*.a from the keyboardevents
project to your project's Build Phases ➜ Link Binary With Libraries Click
.xcodeproj file you added before in the project navigator and go the Build
Settings tab. Make sure 'All' is toggled on (instead of 'Basic').
Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React and $(SRCROOT)/../../React - mark
both as recursive.
Run your project (Cmd+R)
Then back in javascript land:
You need to import the react-native-keyboardevents.
var KeyboardEvents = require('react-native-keyboardevents');
var KeyboardEventEmitter = KeyboardEvents.Emitter;
Then in your view, add some state for the keyboard space and update from listening to the keyboard events.
getInitialState: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, (frames) => {
this.setState({keyboardSpace: frames.end.height});
});
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, (frames) => {
this.setState({keyboardSpace: 0});
});
return {
keyboardSpace: 0,
};
},
Finally, add a spacer to your render function beneath everything so when it increases size it bumps your stuff up.
<View style={{height: this.state.keyboardSpace}}></View>
It is also possible to use the animation api, but for simplicity's sake we just adjust after the animation.
react-native-keyboard-aware-scroll-view solved the problem for me.
react-native-keyboard-aware-scroll-view on GitHub
Try this:
import React, {
DeviceEventEmitter,
Dimensions
} from 'react-native';
...
getInitialState: function() {
return {
visibleHeight: Dimensions.get('window').height
}
},
...
componentDidMount: function() {
let self = this;
DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
self.keyboardWillShow(e);
});
DeviceEventEmitter.addListener('keyboardWillHide', function(e: Event) {
self.keyboardWillHide(e);
});
}
...
keyboardWillShow (e) {
let newSize = Dimensions.get('window').height - e.endCoordinates.height;
this.setState({visibleHeight: newSize});
},
keyboardWillHide (e) {
this.setState({visibleHeight: Dimensions.get('window').height});
},
...
render: function() {
return (<View style={{height: this.state.visibleHeight}}>your view code here...</View>);
}
...
It worked for me. The view basically shrinks when the keyboard is displayed, and grows back again when its hidden.
Just wanted to mention, now there is a KeyboardAvoidingView in RN. Just import it and use it as any other module in RN.
Here is the link to the commit on RN:
https://github.com/facebook/react-native/commit/8b78846a9501ef9c5ce9d1e18ee104bfae76af2e
It is available from 0.29.0
They have also included an example on UIExplorer.
Maybe is to late, but the best solution is to use a native library, IQKeyboardManager
Just drag and drop IQKeyboardManager directory from demo project to your iOS project. That's it. Also you can setup some valus, as isToolbar enabled, or the space between text input and keyboard in the AppDelegate.m file. More details about customisation are in the GitHub page link that I've added.
I used TextInput.onFocus and ScrollView.scrollTo.
...
<ScrollView ref="scrollView">
...
<TextInput onFocus={this.scrolldown}>
...
scrolldown: function(){
this.refs.scrollView.scrollTo(width*2/3);
},
#Stephen
If you don't mind not having the height animate at exactly the same rate that the keyboard appears, you can just use LayoutAnimation, so that at least the height doesn't jump into place. e.g.
import LayoutAnimation from react-native and add the following methods to your component.
getInitialState: function() {
return {keyboardSpace: 0};
},
updateKeyboardSpace: function(frames) {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: frames.end.height});
},
resetKeyboardSpace: function() {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: 0});
},
componentDidMount: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
componentWillUnmount: function() {
KeyboardEventEmitter.off(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
Some example animations are (I'm using the spring one above):
var animations = {
layout: {
spring: {
duration: 400,
create: {
duration: 300,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.spring,
springDamping: 400,
},
},
easeInEaseOut: {
duration: 400,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.scaleXY,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
},
},
};
UPDATE:
See #sherlock's answer below, as of react-native 0.11 the keyboard resizing can be solved using built in functionality.
You can combine a few of the methods into something a little simpler.
Attach a onFocus listener on your inputs
<TextInput ref="password" secureTextEntry={true}
onFocus={this.scrolldown.bind(this,'password')}
/>
Our scroll down method looks something like :
scrolldown(ref) {
const self = this;
this.refs[ref].measure((ox, oy, width, height, px, py) => {
self.refs.scrollView.scrollTo({y: oy - 200});
});
}
This tells our scroll view (remember to add a ref) to scroll to down to the position of our focused input - 200 (it's roughly the size of the keyboard)
componentWillMount() {
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardWillHide',
this.keyboardDidHide.bind(this)
)
}
componentWillUnmount() {
this.keyboardDidHideListener.remove()
}
keyboardDidHide(e) {
this.refs.scrollView.scrollTo({y: 0});
}
Here we reset our scroll view back to the top,
I'm using a simpler method, but it's not animated yet. I have a component state called "bumpedUp" which I default to 0, but set to 1 when the textInput gets focus, like this:
On my textInput:
onFocus={() => this.setState({bumpedUp: 1})}
onEndEditing={() => this.setState({bumpedUp: 0})}
I also have style that gives the wrapping container of everything on that screen a bottom margin and negative top margin, like this:
mythingscontainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
},
bumpedcontainer: {
marginBottom: 210,
marginTop: -210,
},
And then on the wrapping container, I set the styles like this:
<View style={[styles.mythingscontainer, this.state.bumpedUp && styles.bumpedcontainer]}>
So, when the "bumpedUp" state gets set to 1, the bumpedcontainer style kicks in and moves the content up.
Kinda hacky and the margins are hardcoded, but it works :)
I use brysgo answer to raise the bottom of my scrollview. Then I use the onScroll to update the current position of the scrollview. I then found this React Native: Getting the position of an element to get the position of the textinput. I then do some simple math to figure out if the input is in the current view. Then I use scrollTo to move the minimum amount plus a margin. It's pretty smooth. Heres the code for the scrolling portion:
focusOn: function(target) {
return () => {
var handle = React.findNodeHandle(this.refs[target]);
UIManager.measureLayoutRelativeToParent( handle,
(e) => {console.error(e)},
(x,y,w,h) => {
var offs = this.scrollPosition + 250;
var subHeaderHeight = (Sizes.width > 320) ? Sizes.height * 0.067 : Sizes.height * 0.077;
var headerHeight = Sizes.height / 9;
var largeSpace = (Sizes.height - (subHeaderHeight + headerHeight));
var shortSpace = largeSpace - this.keyboardOffset;
if(y+h >= this.scrollPosition + shortSpace) {
this.refs.sv.scrollTo(y+h - shortSpace + 20);
}
if(y < this.scrollPosition) this.refs.sv.scrollTo(this.scrollPosition - (this.scrollPosition-y) - 20 );
}
);
};
},
I also meet this question. Finally, I resolve it by defining the height of each scene, such as:
<Navigator
...
sceneStyle={{height: **}}
/>
And, I also use a third-party module https://github.com/jaysoo/react-native-extra-dimensions-android to get the real height.

Categories

Resources