ios - Cropping and placing image to achieve battery level effect -


i trying achieve battery level effect drawing on plain battery image cropped image based on current battery level.

at moment able change colour of empty battery image don't know how crop, new one, , place on top of original.

i've found useful links on how crop but, every single of them, cropping top-left corner of image. have starting point bottom-left , set height according current level.

in addition, possible combine or place cropped image on top of original?

here original image.

enter image description here

...and trying achieve

enter image description here

at moment trying code,

int width = emptybm.size.width; int height = fullbm.size.height * level / 100;  uiimage *image = [uiimage imagenamed:@"battery_icon"]; uiimage *image2 = [uiimage imagenamed:@"battery_icon_full"];  cgrect rect = cgrectmake(0, image.size.height-height, width, height); cgimageref imageref = cgimagecreatewithimageinrect([image2 cgimage], rect);  cgimageref actualmask = cgimagemaskcreate(cgimagegetwidth([image cgimage]),                                               cgimagegetheight([image cgimage]),                                               cgimagegetbitspercomponent([image cgimage]),                                               cgimagegetbitsperpixel([image cgimage]),                                               cgimagegetbytesperrow([image cgimage]),                                               cgimagegetdataprovider([image cgimage]), null, false); cgimageref masked = cgimagecreatewithmask(imageref, actualmask);  batterybackground.image = [uiimage imagewithcgimage:masked]; 

however, because using cgimagecreatewithimageinrect cropped part stretched

use gray battery image mask. create green rectangle , apply mask created. here link ios masking: link

edit: hope works (not tested):

int width = emptybm.size.width; int height = fullbm.size.height * level / 100;  uiimage *image = [uiimage imagenamed:@"battery_icon"]; uiimage *image2 = [uiimage imagenamed:@"battery_icon_full"];  // clarity, pretend mask method gave link defined in class. uiimage *maskedimage = [self maskimage:image2 withmask:image];  // assume 2 imageviews connected outlets. self.backgroundimageview = [[uiimageview alloc] initwithimage:image]; self.foregroundimageview = [[uiimageview alloc] initwithimage:maskedimage];  // make it's image stick bottom won't stretch. self.foregroundimageview.contentmode = uiviewcontentmodebottom;  // calculate frame again reflect changes of battery status. cgrect rect = self.backgroundimageview.frame; rect.size.height = height; // push masked imageview bottom amount of missing battery height. rect.origin.y = rect.origin.y + self.backgroundimageview.frame.size.height - height; self.foregroundimageview.frame = rect; 

Comments