0

我试图通过在普通电池图像上绘制另一个基于当前电池电量的裁剪图像来实现电池电量效果。

目前我可以更改空电池图像的颜色,但我不知道如何裁剪新的,并将其放在原件的顶部。

我找到了一些关于如何裁剪的有用链接,但是每个链接都是从图像的左上角裁剪的。我想以左下角为起点并根据当前级别设置高度。

此外,是否可以将裁剪后的图像组合或放置在原始图像之上?

这是我的原始图像。

在此处输入图像描述

...以及我想要实现的目标

在此处输入图像描述

目前我正在尝试这段代码,

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的是裁剪部分被拉伸

4

1 回答 1

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;
于 2013-07-11T12:05:34.523 回答