我试图通过在普通电池图像上根据当前电池电量绘制另一个裁剪图像来达到电池电量效果。
此刻,我可以更改空电池图像的颜色,但我不知道如何裁剪,新的,并将其放在原件的顶部。
我找到了一些关于如何裁剪的有用链接,但是,每一个都是从图像的左上角裁剪。我想以左下角为起点,根据当前水平设置高度。
此外,可以将裁剪后的图像组合或放置在原始图像的顶部吗?
这是我的原始图片。
......以及我想要实现的目标
目前我正在尝试此代码,
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];
但是,因为我使用CGImageCreateWithImageInRect
裁剪的部分是拉伸
答案 0 :(得分:2)
使用灰色电池图像作为遮罩。创建一个绿色矩形并应用您创建的蒙版。以下是iOS屏蔽的链接:link
修改强> 我希望这有效(未经测试):
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"];
// For clarity, just pretend the mask method I gave link to you is defined in your class.
UIImage *maskedImage = [self maskImage:image2 withMask:image];
// I assume the two imageviews are already connected to outlets.
self.backgroundImageView = [[UIImageView alloc] initWithImage:image];
self.foregroundImageView = [[UIImageView alloc] initWithImage:maskedImage];
// Make it's image stick to bottom so it won't stretch.
self.foregroundImageView.contentMode = UIViewContentModeBottom;
// Then calculate the frame again to reflect changes of battery status.
CGRect rect = self.backgroundImageView.frame;
rect.size.height = height;
// Push the masked imageview a to bottom as amount of missing battery height.
rect.origin.y = rect.origin.y + self.backgroundImageView.frame.size.height - height;
self.foregroundImageView.frame = rect;