gre / gl-react

gl-react – React library to write and compose WebGL shaders

Home Page:https://gl-react-cookbook.surge.sh

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question - how do I load a react native image?

cris-santos opened this issue · comments

library version

react-native@0.48.2

yarn list v0.24.6
├─ gl-react-native@3.13.0
└─ gl-react@3.13.0

My code

// @flow
import React, { Component } from 'react';
import { Image } from 'react-native';
import { Shaders, Node, GLSL } from 'gl-react';
import { Surface } from 'gl-react-native';

import { images } from '../../theme';

const shaders = Shaders.create({
  blendMultiply: {
    frag: GLSL`
    precision highp float;
    varying vec2 uv;

    uniform sampler2D tex;
    uniform vec4 color;

    vec3 blendMultiply(vec3 base, vec3 blend) {
      return base*blend;
    }
    vec3 blendMultiply(vec3 base, vec3 blend, float opacity) {
      return (blendMultiply(base, blend) * opacity + blend * (1.0 - opacity));
    }

    void main () {
      vec4 baseColor = texture2D(tex, uv);
      vec3 newColor = blendMultiply(baseColor.rgb, color.rgb, color.a);
      gl_FragColor = vec4(newColor, 1.);
    }`,
  },
});


export const BlendMultiply = ({ children: tex, color }) => (
  <Node shader={shaders.blendMultiply} uniforms={{ tex, color }} />
);

export default class Example extends Component {
  render() {
    return (
      <Surface style={{ height: 300, width: 300 }}>
        <BlendMultiply color={[0.1, 0.9, 0.1, 1]}>
          <Image source={images.sample.background} /> // <~ returns null :(
        </BlendMultiply>
      </Surface>
    );
  }
};

you can't give a react-native Image element inside gl-react but this should work instead:

<Surface style={{ height: 300, width: 300 }}>
  <BlendMultiply color={[0.1, 0.9, 0.1, 1]}>
    {images.sample.background}
  </BlendMultiply>
</Surface>

if you are looking for cropping feature (like the RN Image resizeMode), you can also use gl-react-image

e.g.

<Surface style={{ height: 300, width: 300 }}>
  <BlendMultiply color={[0.1, 0.9, 0.1, 1]}>
    <GLImage source={images.sample.background} resizeMode="cover" />
  </BlendMultiply>
</Surface>

Made it work with GLImage, thank a lot!