用到了四个文件:
UIImage+ColorAtPixel.h UIImage+ColorAtPixel.m OBShapedButton.h OBShapedButton.m
作者:Ole Begemann
1 /* 2 Copyright (c) 2009 Ole Begemann 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 /* 24 UIImage+ColorAtPixel.h 25 26 Created by Ole Begemann 27 October, 2009 28 */ 29 30 #import <UIKit/UIKit.h> 31 32 /* 33 A category on UIImage that enables you to query the color value of arbitrary 34 pixels of the image. 35 */ 36 @interface UIImage (ColorAtPixel) 37 38 - (UIColor *)colorAtPixel:(CGPoint)point; 39 40 @end
1 /* 2 Copyright (c) 2009 Ole Begemann 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 /* 24 UIImage+ColorAtPixel.m 25 26 Created by Ole Begemann 27 October, 2009 28 */ 29 30 #import <CoreGraphics/CoreGraphics.h> 31 32 #import "UIImage+ColorAtPixel.h" 33 34 35 @implementation UIImage (ColorAtPixel) 36 37 /* 38 Returns the color of the image pixel at point. Returns nil if point lies outside the image bounds. 39 If the point coordinates contain decimal parts, they will be truncated. 40 41 To get at the pixel data, this method must draw the image into a bitmap context. 42 For minimal memory usage and optimum performance, only the specific requested 43 pixel is drawn. 44 If you need to query pixel colors for the same image repeatedly (e.g., in a loop), 45 this approach is probably less efficient than drawing the entire image into memory 46 once and caching it. 47 */ 48 - (UIColor *)colorAtPixel:(CGPoint)point { 49 // Cancel if point is outside image coordinates 50 if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) { 51 return nil; 52 } 53 54 55 // Create a 1x1 pixel byte array and bitmap context to draw the pixel into. 56 // Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage 57 NSInteger pointX = trunc(point.x); 58 NSInteger pointY = trunc(point.y); 59 CGImageRef cgImage = self.CGImage; 60 NSUInteger width = self.size.width; 61 NSUInteger height = self.size.height; 62 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 63 int bytesPerPixel = 4; 64 int bytesPerRow = bytesPerPixel * 1; 65 NSUInteger bitsPerComponent = 8; 66 unsigned char pixelData[4] = { 0, 0, 0, 0 }; 67 CGContextRef context = CGBitmapContextCreate(pixelData, 68 1, 69 1, 70 bitsPerComponent, 71 bytesPerRow, 72 colorSpace, 73 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 74 CGColorSpaceRelease(colorSpace); 75 CGContextSetBlendMode(context, kCGBlendModeCopy); 76 77 // Draw the pixel we are interested in onto the bitmap context 78 CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height); 79 CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage); 80 CGContextRelease(context); 81 82 // Convert color values [0..255] to floats [0.0..1.0] 83 CGFloat red = (CGFloat)pixelData[0] / 255.0f; 84 CGFloat green = (CGFloat)pixelData[1] / 255.0f; 85 CGFloat blue = (CGFloat)pixelData[2] / 255.0f; 86 CGFloat alpha = (CGFloat)pixelData[3] / 255.0f; 87 return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; 88 } 89 90 @end
1 /* 2 Copyright (c) 2009 Ole Begemann 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 /* 24 OBShapedButton.h 25 26 Created by Ole Begemann 27 October, 2009 28 */ 29 30 #import <UIKit/UIKit.h> 31 32 33 /* 34 OBShapedButton is a UIButton subclass optimized for non-rectangular button shapes. 35 Instances of OBShapedButton respond to touches only in areas where the image that is 36 assigned to the button for UIControlStateNormal is non-transparent. 37 38 Usage: 39 - Add OBShapedButton.h, OBShapedButton.m, UIImage+ColorAtPixel.h, and UIImage+ColorAtPixel.m 40 to your Xcode project. 41 - Design your UI in Interface Builder with UIButtons as usual. Set the Button type to Custom 42 and provide transparent PNG images for the different control states as needed. 43 - In the Identity Inspector in Interface Builder, set the Class of the button to OBShapedButton. 44 That's it! Your button will now only respond to touches where the PNG image for the normal 45 control state is non-transparent. 46 */ 47 48 49 50 // -[UIView hitTest:withEvent: ignores views that an alpha level less than 0.1. 51 // So we will do the same and treat pixels with alpha < 0.1 as transparent. 52 #define kAlphaVisibleThreshold (0.1f) 53 54 55 @interface OBShapedButton : UIButton { 56 // Our class interface is empty. OBShapedButton only overwrites one method of UIView. 57 // It has no attributes of its own. 58 } 59 60 @end
1 /* 2 Copyright (c) 2009 Ole Begemann 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 /* 24 OBShapedButton.m 25 26 Created by Ole Begemann 27 October, 2009 28 */ 29 30 #import "OBShapedButton.h" 31 #import "UIImage+ColorAtPixel.h" 32 33 34 @interface OBShapedButton () 35 36 @property (nonatomic, assign) CGPoint previousTouchPoint; 37 @property (nonatomic, assign) BOOL previousTouchHitTestResponse; 38 39 - (void)resetHitTestCache; 40 41 @end 42 43 44 @implementation OBShapedButton 45 46 @synthesize previousTouchPoint = _previousTouchPoint; 47 @synthesize previousTouchHitTestResponse = _previousTouchHitTestResponse; 48 49 - (id)initWithFrame:(CGRect)frame 50 { 51 self = [super initWithFrame:frame]; 52 if (self) { 53 [self resetHitTestCache]; 54 } 55 return self; 56 } 57 58 - (id)initWithCoder:(NSCoder *)decoder 59 { 60 self = [super initWithCoder:decoder]; 61 if (self) { 62 [self resetHitTestCache]; 63 } 64 return self; 65 } 66 67 68 #pragma mark - Hit testing 69 70 - (BOOL)isAlphaVisibleAtPoint:(CGPoint)point forImage:(UIImage *)image 71 { 72 // Correct point to take into account that the image does not have to be the same size 73 // as the button. See https://github.com/ole/OBShapedButton/issues/1 74 CGSize iSize = image.size; 75 CGSize bSize = self.bounds.size; 76 point.x *= (bSize.width != 0) ? (iSize.width / bSize.width) : 1; 77 point.y *= (bSize.height != 0) ? (iSize.height / bSize.height) : 1; 78 79 CGColorRef pixelColor = [[image colorAtPixel:point] CGColor]; 80 CGFloat alpha = CGColorGetAlpha(pixelColor); 81 return alpha >= kAlphaVisibleThreshold; 82 } 83 84 85 // UIView uses this method in hitTest:withEvent: to determine which subview should receive a touch event. 86 // If pointInside:withEvent: returns YES, then the subview’s hierarchy is traversed; otherwise, its branch 87 // of the view hierarchy is ignored. 88 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event 89 { 90 // Return NO if even super returns NO (i.e., if point lies outside our bounds) 91 BOOL superResult = [super pointInside:point withEvent:event]; 92 if (!superResult) { 93 return superResult; 94 } 95 96 // Don't check again if we just queried the same point 97 // (because pointInside:withEvent: gets often called multiple times) 98 if (CGPointEqualToPoint(point, self.previousTouchPoint)) { 99 return self.previousTouchHitTestResponse; 100 } else { 101 self.previousTouchPoint = point; 102 } 103 104 // We can't test the image's alpha channel if the button has no image. Fall back to super. 105 UIImage *buttonImage = [self imageForState:UIControlStateNormal]; 106 UIImage *buttonBackground = [self backgroundImageForState:UIControlStateNormal]; 107 108 BOOL response = NO; 109 110 if (buttonImage == nil && buttonBackground == nil) { 111 response = YES; 112 } 113 else if (buttonImage != nil && buttonBackground == nil) { 114 response = [self isAlphaVisibleAtPoint:point forImage:buttonImage]; 115 } 116 else if (buttonImage == nil && buttonBackground != nil) { 117 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground]; 118 } 119 else { 120 if ([self isAlphaVisibleAtPoint:point forImage:buttonImage]) { 121 response = YES; 122 } else { 123 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground]; 124 } 125 } 126 127 self.previousTouchHitTestResponse = response; 128 return response; 129 } 130 131 132 // Reset the Hit Test Cache when a new image is assigned to the button 133 - (void)setImage:(UIImage *)image forState:(UIControlState)state 134 { 135 [super setImage:image forState:state]; 136 [self resetHitTestCache]; 137 } 138 139 - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state 140 { 141 [super setBackgroundImage:image forState:state]; 142 [self resetHitTestCache]; 143 } 144 145 - (void)resetHitTestCache 146 { 147 self.previousTouchPoint = CGPointMake(CGFLOAT_MIN, CGFLOAT_MIN); 148 self.previousTouchHitTestResponse = NO; 149 } 150 151 @end
使用:
使用IB,添加一个UIButton,把关联类选择为OBShapedButton,把Button的Type修改为Custom,添加一个异形的Image,然后编译运行即可看到效果。