更新时间:2023-11-26 23:49:22
你需要在位图上下文中创建图像的副本,通过绘制叠加或以某种方式处理它来修改副本,然后将修改后的图像分配给按钮的 UIControlStateSelected
状态。
You need to create a copy of the image in a bitmap context, modify the copy by drawing an overlay or processing it in some way, and then assign the modified image to the button's UIControlStateSelected
state.
下面是一些示例代码,用于创建上下文并在图像上为按钮的选定状态绘制50%的黑色覆盖图,使其变暗:
Here is some sample code that creates the context and draws a 50% black overlay on the image for the selected state of the button, which darkens it:
//assume UIImage* image exists
//get the size of the image
CGFloat pixelsHigh = image.size.height;
CGFloat pixelsWide = image.size.width;
//create a new context the same size as the image
CGContextRef cx = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return;
}
cx = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (cx == NULL)
{
free (bitmapData);
fprintf (stderr, "Context not created!");
return;
}
CGColorSpaceRelease( colorSpace );
CGRect imageRect = CGRectMake(0, 0, pixelsWide, pixelsHigh);
//draw the existing image in the context
CGContextDrawImage(cx, imageRect, image.CGImage);
//draw a 50% black overlay
CGContextSetRGBFillColor(cx, 0, 0, 0, 0.5);
CGContextFillRect(cx, imageRect);
//create a new image from the context
CGImageRef newImage = CGBitmapContextCreateImage(cx);
UIImage* secondaryImage = [UIImage imageWithCGImage:newImage];
CGImageRelease(newImage);
CGContextRelease(cx);
//assign the images to the button
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setBackgroundImage:secondaryImage forState:UIControlStateSelected];