Equivalent Android 9-patch for iOS and Swift 3.0 (multiple stretchable areas)

5.5k views Asked by At

I'm new to Swift and iOS. In Android we can easily stretched an image and put some contents inside this image, but I don't find any equivalent for iOS.

I found a lot of tutorial/post with the resizableImage(withCapInsets) method but it is not exactly what I want. Look this image :

stretchable areas with resizableImage

The areas 2, 4, 5, 6 and 8 will be stretched and only them. With the Android 9-patch, I can define multiple stretchable areas like below :

multiple stretchable areas

Here, only the red areas are stretchable. This method is really useful to keep the green area fixed, but it is impossible with resizableImage(withCapInsets).

Furthermore, with the Android 9-patch, we can define easily an area of content like texview, imageview, ..., in the blue area and the image stretches according to the text size in this area. Is it possible with iOS and Swift ?

2

There are 2 answers

1
Duncan C On BEST ANSWER

As far as I know resizableImage(withCapInsets:) is your only built-in option, and the system does not support your 2nd scenario with 2 stretchable areas.

As mentioned in the other thread Jon Rose linked to, it should be possible to accomplish your goal using 2 image views. I would suggest creating a subclass of UIImageView that offers this functionality and internally breaks the image into 2 pices and creates a separate stretchable image for both. It shouldn't be that hard to do.

After a little googling it looks like somebody else has already created an iOS 9-patch image library. Check out this link: https://github.com/andyland/Tortuga22-NinePatch

Unfortunately the readme link on that repo is broken, so you'll have to download it and poke around to figure out how out how to use it. As to why the readme was put in as a link rather than inline, I have no idea.

0
Michał Ziobro On

You can youse CALayer and its contentsRect combined with contentsCenter. contentCenter defines CGRect of horizontally/vertically streching area. Remaining eight parts corners and onedirectional streching edges are inferred based on contentsCenter and contentsRect. But i think it is more complicated approach then android solution.