使用网上开源代码:
UIImage+ColorAtPixel.h 及 UIImage+ColorAtPixel.m
不规则button: OBShapedButton
不规则view: OBShapeView (自己参考上面的开源代码实现的)
UIImage+ColorAtPixel.h :
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
UIImage+ColorAtPixel.m :
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
OBShapedButton.h :
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 { 57 // Our class interface is empty. OBShapedButton only overwrites one method of UIView. 58 // It has no attributes of its own. 59 } 60 61 @end
OBShapedButton.m :
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 42 @end 43 44 45 @implementation OBShapedButton 46 47 @synthesize previousTouchPoint = _previousTouchPoint; 48 @synthesize previousTouchHitTestResponse = _previousTouchHitTestResponse; 49 50 - (id)initWithFrame:(CGRect)frame 51 { 52 self = [super initWithFrame:frame]; 53 if (self) { 54 [self resetHitTestCache]; 55 } 56 return self; 57 } 58 59 - (id)initWithCoder:(NSCoder *)decoder 60 { 61 self = [super initWithCoder:decoder]; 62 if (self) { 63 [self resetHitTestCache]; 64 } 65 return self; 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 { 112 response = YES; 113 } 114 else if (buttonImage != nil && buttonBackground == nil) 115 { 116 response = [self isAlphaVisibleAtPoint:point forImage:buttonImage]; 117 } 118 else if (buttonImage == nil && buttonBackground != nil) 119 { 120 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground]; 121 } 122 else 123 { 124 if ([self isAlphaVisibleAtPoint:point forImage:buttonImage]) 125 { 126 response = YES; 127 } else 128 { 129 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground]; 130 } 131 } 132 133 self.previousTouchHitTestResponse = response; 134 return response; 135 } 136 137 138 // Reset the Hit Test Cache when a new image is assigned to the button 139 - (void)setImage:(UIImage *)image forState:(UIControlState)state 140 { 141 [super setImage:image forState:state]; 142 [self resetHitTestCache]; 143 } 144 145 - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state 146 { 147 [super setBackgroundImage:image forState:state]; 148 [self resetHitTestCache]; 149 } 150 151 - (void)resetHitTestCache 152 { 153 self.previousTouchPoint = CGPointMake(CGFLOAT_MIN, CGFLOAT_MIN); 154 self.previousTouchHitTestResponse = NO; 155 } 156 157 @end
OBShapeView.h :
1 // 2 // OBShapeView.h 3 // shapeBtn 4 // 5 // Created by qqc on 13-7-23. 6 // Copyright (c) 2013年 qqc. All rights reserved. 7 // 8 9 #import <UIKit/UIKit.h> 10 11 12 #define kAlphaVisibleThreshold_view (0.1f) 13 14 @interface OBShapeView : UIView 15 16 - (void)setBackgroundImage:(UIImage *)image; 17 18 @end
OBShapeView.m :
1 // 2 // OBShapeView.m 3 // shapeBtn 4 // 5 // Created by qqc on 13-7-23. 6 // Copyright (c) 2013年 qqc. All rights reserved. 7 // 8 9 #import "OBShapeView.h" 10 #import "UIImage+ColorAtPixel.h" 11 12 @interface OBShapeView() 13 14 @property (nonatomic, assign) CGPoint previousTouchPoint; 15 @property (nonatomic, assign) BOOL previousTouchHitTestResponse; 16 @property (nonatomic, strong) UIImageView* imageView; 17 18 - (void)resetHitTestCache; 19 20 @end 21 22 @implementation OBShapeView 23 24 @synthesize previousTouchPoint = _previousTouchPoint; 25 @synthesize previousTouchHitTestResponse = _previousTouchHitTestResponse; 26 @synthesize imageView = _imageView; 27 28 - (id)initWithFrame:(CGRect)frame 29 { 30 self = [super initWithFrame:frame]; 31 if (self) 32 { 33 [self resetHitTestCache]; 34 self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,frame.size.width,frame.size.height)]; 35 [self addSubview:self.imageView]; 36 } 37 return self; 38 } 39 40 41 - (void)setBackgroundImage:(UIImage *)image 42 { 43 [self.imageView setImage:image]; 44 [self resetHitTestCache]; 45 } 46 47 - (void)resetHitTestCache 48 { 49 self.previousTouchPoint = CGPointMake(CGFLOAT_MIN, CGFLOAT_MIN); 50 self.previousTouchHitTestResponse = NO; 51 } 52 53 #pragma mark - Hit testing 54 - (BOOL)isAlphaVisibleAtPoint:(CGPoint)point forImage:(UIImage *)image 55 { 56 // Correct point to take into account that the image does not have to be the same size 57 // as the button. See https://github.com/ole/OBShapedButton/issues/1 58 CGSize iSize = image.size; 59 CGSize bSize = self.bounds.size; 60 point.x *= (bSize.width != 0) ? (iSize.width / bSize.width) : 1; 61 point.y *= (bSize.height != 0) ? (iSize.height / bSize.height) : 1; 62 63 CGColorRef pixelColor = [[image colorAtPixel:point] CGColor]; 64 CGFloat alpha = CGColorGetAlpha(pixelColor); 65 return alpha >= kAlphaVisibleThreshold_view; 66 } 67 68 69 // UIView uses this method in hitTest:withEvent: to determine which subview should receive a touch event. 70 // If pointInside:withEvent: returns YES, then the subview’s hierarchy is traversed; otherwise, its branch 71 // of the view hierarchy is ignored. 72 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event 73 { 74 // Return NO if even super returns NO (i.e., if point lies outside our bounds) 75 BOOL superResult = [super pointInside:point withEvent:event]; 76 if (!superResult) { 77 return superResult; 78 } 79 80 // Don't check again if we just queried the same point 81 // (because pointInside:withEvent: gets often called multiple times) 82 if (CGPointEqualToPoint(point, self.previousTouchPoint)) { 83 return self.previousTouchHitTestResponse; 84 } else { 85 self.previousTouchPoint = point; 86 } 87 88 // We can't test the image's alpha channel if the button has no image. Fall back to super. 89 UIImage *bgImage = self.imageView.image; 90 91 BOOL response = NO; 92 93 if (bgImage == nil) 94 { 95 response = YES; 96 } 97 else if (bgImage != nil) 98 { 99 response = [self isAlphaVisibleAtPoint:point forImage:bgImage]; 100 } 101 102 self.previousTouchHitTestResponse = response; 103 return response; 104 } 105 106 @end
使用范例:
1 //不规则窗口 2 self.obView = [[OBShapeView alloc] initWithFrame:CGRectMake(0, 400, 320, 68)]; 3 [self.obView setBackgroundImage:[UIImage imageNamed:@"button-normal.png"]]; 4 [self.view addSubview:self.obView]; 5 6 OBShapedButton* btn = [[OBShapedButton alloc] initWithFrame:CGRectMake(100, 30, 120, 30)]; 7 [btn setImage:[UIImage imageNamed:@"complex-normal.png"] forState:UIControlStateNormal]; 8 9 [self.obView addSubview:btn];