3

I have a slider component which I want to have a handle as png image pass as a prop. Now, I want that png image to pass through react native to native modules(android and ios both). The component is written at native side for both ios(Objective C) and android(Java).

  1. How can I pass png image as a prop to native modules?
  2. How can I use them at native Java part?(I am using Canvas to draw my slider as shown below).
  3. How can I use them at native Objective C?(I am using CGContext to draw my slider).

What I have tried:

  1. I resolved path of png image by following code at React Native side.
  const myImage = require('../assets/slider-handle.png');
  const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
  const resolvedImage = resolveAssetSource(myImage); 

Then pass the path of image as a prop imagePath={resolvedImage.uri}.

Then at Java part I do following:

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

I am getting the path of image(the path is something like this: (http:/10.0.2.2:8081/assets/app/components/slider/assets/slider.png), I have verified that at native side by consoling the path.

Not sure if I need to pass only path of image or maybe there is a way to pass whole png. This is my first time working with Java and Objective C. This is the slider I am developing. Any help will be really appreciated.

0

1 Answer 1

1

I see that the thread is quite old, but this can be useful in the future.

A way that works for me is encoding the bitmap to Base64.

Java Side:

iconBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);

React-native side:

   <Image source={{uri: `data:image/png;base64,${props.item.iconBase64}`}}/>

If needed you can even compress the image:

bitmap.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
Sign up to request clarification or add additional context in comments.

1 Comment

it was useful, here is a method in java ` private String convertBitmapToBase64(Bitmap bitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); return Base64.encodeToString(byteArray, Base64.DEFAULT); } `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.