How to define image as a background button

Viewed 25814

I try this code to make image as background for button :

      <Button  style= {styles.btn }>
          <Image source={ require('.src.png')}  style={styles.img}/>
          <Text> title </Text> 
      </Button>

But I don't get the correct result Any help, please

3 Answers

Here is a simple ImageButton

import React from 'react'
import { TouchableOpacity, View, Image, Text, StyleSheet } from 'react-native'
import images from 'res/images'
import colors from 'res/colors'

export default class ImageButton extends React.Component {
  render() {
    return (
      <TouchableOpacity style={styles.touchable}>
        <View style={styles.view}>
          <Text style={styles.text}>{this.props.title}</Text>
        </View>
        <Image
          source={images.button}
          style={styles.image} />
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  view: {
    position: 'absolute',
    backgroundColor: 'transparent'
  },
  image: {

  },
  touchable: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    color: colors.button,
    fontSize: 18,
    textAlign: 'center'
  }
})

Use TouchableOpacity and ImageBackground from "react-native" like this:

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ImageBackground,
} from "react-native";

export default function App() {
  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={() => alert("Button pressed")}>
        <ImageBackground source={require("./assets/anImage.png")} style={{}}>
          <Text style={styles.title}>Press Me</Text>
        </ImageBackground>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    color: "white",
    fontSize: 24,
    padding: 20,
  }
});
Related