요즘 코로나라 앱에서 QR을 많이 사용하는데  QR Code 만드는 법을 봅시다.

 

www.npmjs.com/package/react-native-qrcode-svg

 

react-native-qrcode-svg

A QR Code generator for React Native based on react-native-svg and javascript-qrcode.

www.npmjs.com

위 라이브러리를 사용했습니다.

 

안드로이드

 

ios

 

 

yarn add react-native-svg react-native-qrcode-svg

yarn add react-native-svg react-native-qrcode-svg

 

npm i -S react-native-svg react-native-qrcode-svg

npm i -S react-native-svg react-native-qrcode-svg

으로 라이브러리를 install합니다.

 

react-native version이 <=0.59.X 라면 link를 꼭 해줘야합니다.

 

react-native link react-native-svg

react-native link react-native-svg

 

도큐먼트에 있는 example Code 들 입니다.

 

import QRCode from 'react-native-qrcode-svg';

// Simple usage, defaults for all but the value
render() {
  return (
    <QRCode
      value="http://awesome.link.qr"
    />
  );
};

 

// 30px logo from base64 string with transparent background
render() {
  let base64Logo = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAA..';
  return (
    <QRCode
      value="Just some string value"
      logo={{uri: base64Logo}}
      logoSize={30}
      logoBackgroundColor='transparent'
    />
  );
};

 

// 20% (default) sized logo from local file string with white logo backdrop
render() {
  let logoFromFile = require('../assets/logo.png');
  return (
    <QRCode
      value="Just some string value"
      logo={logoFromFile}
    />
  );
};

 

// get base64 string encode of the qrcode (currently logo is not included)
getDataURL() {
  this.svg.toDataURL(this.callback);
}

callback(dataURL) {
  console.log(dataURL);
}

render() {
  return (
    <QRCode
      value="Just some string value"
      getRef={(c) => (this.svg = c)}
    />
  );
}

 

등 다양한 형태로 쓸 수 있습니다.

저는 이렇게 사용했습니다.

 

 import QRCode from 'react-native-qrcode-svg';
 
 
 <View style={styles.qrCodeStyle}>
   <View>
     <QRCode
       size= {200}			  // 로고 사이즈 조절
       value={data.address}   // 실제 연결 될 주소 
       logoSize={300}		  
       logoBackgroundColor='transparent'
     />
   </View>
 </View>
 
 

그러면 QR Code가 나옵니다.

Props

NameDefaultDescription

size  - 렌더링 된 이미지의 크기(픽셀) 100 Size of rendered image in pixels
value - QR 코드 값 'this is a QR code' String Value of the QR code. Can also accept an array of segments as defined in Manual mode. Ex. [{ data: 'ABCDEFG', mode: 'alphanumeric' }, { data: '0123456', mode: 'numeric' }, { data: [253,254,255], mode: 'byte' }]
color - QR 코드의 색상 'black' Color of the QR code
backgroundColor - 배경색 'white' Color of the background
enableLinearGradient - Gradient 활성화, 비활성화 false enables or disables linear gradient
linearGradient - 선형 Gradient 만드는데 사용되는 2개의 RGB 색상 배열 ['rgb(255,0,0)','rgb(0,255,255)'] array of 2 rgb colors used to create the linear gradient
gradientDirection - 선형 Gradient의
방향
[170,0,0,0] the direction of the linear gradient
logo - 이미지 소스 개체 null Image source object. Ex. {uri: 'base64string'} or {require('pathToImage')}
logoSize - 각인된 로고의 크기 20% of size Size of the imprinted logo. Bigger logo = less error correction in QR code
logoBackgroundColor - 배경색 backgroundColor The logo gets a filled quadratic background with this color. Use 'transparent' if your logo already has its own backdrop.
logoMargin - margin 값 2 logo's distance to its wrapper
logoBorderRadius - Radius 값 0 the border-radius of logo image (Android is not supported)
quietZone - qr주변의 영역 0 quiet zone around the qr in pixels (useful when saving image to gallery)
getRef - svg참조 가져오기 null Get SVG ref for further usage
ecl - 오류 수정 수준 'M' Error correction level
onError(error) - 생성중 예외 발생 시 콜백 발생 undefined Callback fired when exception happened during the code generating process

도큐 먼트에 있는 이 부분을 잘 사용하면 custom 도 잘 될 것 같습니다 !

 

reactnative.dev/docs/imagebackground

 

ImageBackground · React Native

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the ` component, which has the same props as `, and add whatever children to it you would like to layer on top of it.

reactnative.dev

react-native에서 백그라운드 이미지를 넣어봅시다 !

rn에서는 내장함수로 ImageBackground 가 있습니다. js 같은 경우는 스타일에서 background-image: url( ~); 이렇게 주면 백그라운드 이미지가 들어가는데 rn은 

const App = () => (
  <View style={styles.container}>
    <ImageBackground source={image} style={styles.image}>
      <Text style={styles.text}>Inside</Text>
    </ImageBackground>
  </View>
);

이런방법으로 사용해야합니다.

 

저의 같은 경우는 

<ImageBackground style={styles.imgWrapper} source={require('../assets/test.png')} >
      <Text>테스트</Text>
</ImageBackground>

이렇게 사용했습니다.

여기서 중요한점은 style을 사용해줘야 에러가 안납니다. 

감사합니다.

www.npmjs.com/package/react-native-image-picker

 

react-native-image-picker

A React Native module that allows you to use native UI to select media from the device library or directly from the camera

www.npmjs.com

react-native-image-picker 이라는 라이브러리를 소개 해드립니다!!!!

 

첫 번째로는 

android/app/main/AndroidManifest.ml 에

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

이렇게 두줄을 

넣어주세요!

 

그뒤로 코드입니다!

import ImagePicker from 'react-native-image-picker';
 
const [ img, setImageSource ] = useState("");  // 이미지를 img변수에 할당시킬겁니다!

function pickImg() { 
  const options = {
    title: 'Select Avatar', //이미지 선택할 때 제목입니다 ( 타이틀 ) 
    customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }], // 선택 버튼을 커스텀 할 수 있습니다.
    storageOptions: {
      skipBackup: true,	// ios인 경우 icloud 저장 여부 입니다!
      path: 'images',
    },
  };

  /**
   * The first arg is the options object for customization (it can also be null or omitted for default options),
   * The second arg is the callback which sends object: response (more info in the API Reference)
   */
  ImagePicker.showImagePicker(options, (response) => {
    console.log('Response = ', response);

    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      // You can also display the image using data:
      // const source = { uri: 'data:image/jpeg;base64,' + response.data };
      setImageSource(response.uri); // 저는 여기서 uri 값을 저장 시킵니다 !
    }
  });
}

/* return 코드
{img ?   // 이미지가 있으면 라이브러리에서 받아온 이미지로 출력, 없으면 디폴트 이미지 출력!
	<TouchableOpacity style={styles.imgWrapper} onPress={()=>pickImg()}>
		<Image source={{uri: img}} style={styles.imgStyle}/>
	</TouchableOpacity>  
	:
	<TouchableOpacity style={styles.imgWrapper} onPress={()=>pickImg()}>
		<Image source={defaultImg} style={styles.imgStyle}/>
	</TouchableOpacity>
}

                
*/

 

일단 response 값으로 uri나 data 등등 값이 오는데요 여기서 저는 uri 만 필요하기 때문에 setImageSource에 uri를 

저장하고 img에 넣어서 img로 프로필 사진 받아오는 코드를 작성해봤는데요

const options 에

 

const options = {

        title: '사진',

        takePhotoButtonTitle: '카메라',

        chooseFromLibraryButtonTitle: '이미지 선택',
		
        cancelButtonTitle: '취소'
        
      };

이렇게 설정을 해두시면 자기가 원하는 텍스트로 커스텀이 가능합니다 ! 

 

디폴트 이미지
커스텀 한 이미지

 

이미지를 불러와서 저장

 

이렇게 이미지를 저장하고 카메라를 찍을 수 있는 라이브러리를 사용해봤습니다~!~!

어플 개발을 하다보면 기기 등록을 해야할 때가 있을 것 입니다.

os는 무엇인지, 기종은 무엇인지 version은 뭔지 등등 이러한 부분에 궁금증이 생겨 하나하나 찾아보았습니다 !

 

1. device UniqueId, Brand, DeviceId 등

 

https://www.npmjs.com/package/react-native-device-info

 

react-native-device-info

Get device information using react-native

www.npmjs.com

react-native-device-info 라는 npm 입니다. 이 npm 은 많은 디바이스 정보들을 가져올 수 있는 npm 입니다 !

npm install --save react-native-device-info 로 install을 한 뒤

import DeviceInfo from 'react-native-device-info';

사용할 곳에 import를 해줍니다.

그 다음 예제를 보여드리면

let platform = DeviceInfo.getBrand();

이런식으로 값을 담아서 console.log를 찍어보시면 Brand 값을 알 수 있습니다.

 

2. language

https://www.npmjs.com/package/react-native-localize

 

react-native-localize

A toolbox for your React Native app localization.

www.npmjs.com

language등 앱 현지화를 위한 npm 입니다 !

필자는 여기서 language만 가져오고 싶어서 이 npm을 사용했습니다.

 

npm install --save react-native-localize 또는

yarn add react-native-localize

로 install 을 한 뒤

import * as RNLocalize from "react-native-localize";
 
console.log(RNLocalize.getLocales());
console.log(RNLocalize.getCurrencies());
 
RNLocalize.addEventListener("change", () => {
  // do localization related stuff…
});

이런 식으로 example 코드를 사용할 수 있고

  let lang = RNLocalize.getLocales()[0].languageTag;

오브젝트 안에 원하는 값을 찾아서 값을 넣어주었습니다 !

 

3. react-native Platform

react-native 에서도 제공을 하는데요 저는 os, version 등을 알기위해서 사용했습니다.

 

import Platform from 'react-native';

 

 

  let os = Platform.OS;
  let version = Platform.Version;

이런식으로 사용했습니다.

 

이로써 디바이스 정보에 대해서 알아봤습니다 ~~ 

+ Recent posts