Display png image from native module in [React Native] Display png image from native module in [React Native]

Display png image from native module in [React Native]

If you’ve been working on a React Native project and encountered the need to display PNG images in a slider component through native modules, you might have faced some challenges. In this article, we’ll discuss an approach to efficiently pass and use PNG images in both Android and iOS native modules.

Passing PNG Image as a Prop to Native Modules

One way to achieve this is by resolving the path of the PNG image on the React Native side and passing it as a prop to the native modules. Here’s a snippet of how you can accomplish this:

    
const myImage = require('../assets/slider-handle.png');
const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
const resolvedImage = resolveAssetSource(myImage);

// Pass the path of the image as a prop
<YourSliderComponent imagePath={resolvedImage.uri} />
    
    

Using PNG Images in Native Java Part

In the native Java part (Android), you can use the following code snippet to draw the image on the canvas:

    
public void drawImage(String imagePath, Canvas canvas, int x, int y) {
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    canvas.drawBitmap(bitmap, y, x, somePaintValue);
}
    
    

However, if you encounter issues with passing the image path, consider encoding the bitmap to Base64 on the Java side:

    
// Encode the bitmap to Base64
iconBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
    
    

Using PNG Images in Native Objective C Part

For the native Objective C part (iOS), you can utilize the following code snippet to draw the image using CGContext:

    
// Your Objective C code to draw the image using CGContext
    
    

Optimizing PNG Image Display

If you find that passing only the path of the image is not sufficient, you can consider encoding the bitmap to Base64 on the Java side. This can be useful for compressing the image and improving efficiency:

    
// Compress the image if needed
bitmap.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
    
    

By following these steps, you can enhance the performance and functionality of your React Native slider component when dealing with PNG images in native modules for both Android and iOS platforms.