700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 实现不规则形状的按钮

实现不规则形状的按钮

时间:2019-07-04 16:14:49

相关推荐

实现不规则形状的按钮

用到了四个文件:

UIImage+ColorAtPixel.hUIImage+ColorAtPixel.mOBShapedButton.hOBShapedButton.m

作者:Ole Begemann

1 /* 2 Copyright (c) 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 in12 all copies or substantial portions of the Software.13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18 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 IN20 THE SOFTWARE.21 */22 23 /*24 UIImage+ColorAtPixel.h25 26 Created by Ole Begemann27 October, 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

View Code

1 /* 2 Copyright (c) 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 in12 all copies or substantial portions of the Software.13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18 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 IN20 THE SOFTWARE.21 */22 23 /*24 UIImage+ColorAtPixel.m25 26 Created by Ole Begemann27 October, 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 requested43 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 memory46 once and caching it.47 */48 - (UIColor *)colorAtPixel:(CGPoint)point {49// Cancel if point is outside image coordinates50if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point)) {51 return nil;52}535455// Create a 1x1 pixel byte array and bitmap context to draw the pixel into.56// Reference: /questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage57NSInteger pointX = trunc(point.x);58NSInteger pointY = trunc(point.y);59CGImageRef cgImage = self.CGImage;60NSUInteger width = self.size.width;61NSUInteger height = self.size.height;62CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();63int bytesPerPixel = 4;64int bytesPerRow = bytesPerPixel * 1;65NSUInteger bitsPerComponent = 8;66unsigned char pixelData[4] = { 0, 0, 0, 0 };67CGContextRef context = CGBitmapContextCreate(pixelData, 681,691,70bitsPerComponent, 71bytesPerRow, 72colorSpace,73kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);74CGColorSpaceRelease(colorSpace);75CGContextSetBlendMode(context, kCGBlendModeCopy);76 77// Draw the pixel we are interested in onto the bitmap context78CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);79CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);80CGContextRelease(context);8182// Convert color values [0..255] to floats [0.0..1.0]83CGFloat red = (CGFloat)pixelData[0] / 255.0f;84CGFloat green = (CGFloat)pixelData[1] / 255.0f;85CGFloat blue = (CGFloat)pixelData[2] / 255.0f;86CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;87return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];88 }89 90 @end

View Code

1 /* 2 Copyright (c) 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 in12 all copies or substantial portions of the Software.13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18 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 IN20 THE SOFTWARE.21 */22 23 /*24 OBShapedButton.h25 26 Created by Ole Begemann27 October, 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 is36 assigned to the button for UIControlStateNormal is non-transparent.37 38 Usage:39 - Add OBShapedButton.h, OBShapedButton.m, UIImage+ColorAtPixel.h, and UIImage+ColorAtPixel.m40 to your Xcode project.41 - Design your UI in Interface Builder with UIButtons as usual. Set the Button type to Custom42 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 normal45 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

View Code

1 /* 2 Copyright (c) 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, 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 { 51self = [super initWithFrame:frame]; 52if (self) { 53 [self resetHitTestCache]; 54} 55return self; 56 } 57 58 - (id)initWithCoder:(NSCoder *)decoder 59 { 60self = [super initWithCoder:decoder]; 61if (self) { 62 [self resetHitTestCache]; 63} 64return 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 /ole/OBShapedButton/issues/1 74CGSize iSize = image.size; 75CGSize bSize = self.bounds.size; 76point.x *= (bSize.width != 0) ? (iSize.width / bSize.width) : 1; 77point.y *= (bSize.height != 0) ? (iSize.height / bSize.height) : 1; 78 79CGColorRef pixelColor = [[image colorAtPixel:point] CGColor]; 80CGFloat alpha = CGColorGetAlpha(pixelColor); 81return 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) 91BOOL superResult = [super pointInside:point withEvent:event]; 92if (!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) 98if (CGPointEqualToPoint(point, self.previousTouchPoint)) { 99 return self.previousTouchHitTestResponse;100} else {101 self.previousTouchPoint = point;102}103104// We can't test the image's alpha channel if the button has no image. Fall back to super.105UIImage *buttonImage = [self imageForState:UIControlStateNormal];106UIImage *buttonBackground = [self backgroundImageForState:UIControlStateNormal];107 108BOOL response = NO;109110if (buttonImage == nil && buttonBackground == nil) {111 response = YES;112}113else if (buttonImage != nil && buttonBackground == nil) {114 response = [self isAlphaVisibleAtPoint:point forImage:buttonImage];115}116else if (buttonImage == nil && buttonBackground != nil) {117 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground];118}119else {120 if ([self isAlphaVisibleAtPoint:point forImage:buttonImage]) {121 response = YES;122 } else {123 response = [self isAlphaVisibleAtPoint:point forImage:buttonBackground];124 }125}126127self.previousTouchHitTestResponse = response;128return response;129 }130 131 132 // Reset the Hit Test Cache when a new image is assigned to the button133 - (void)setImage:(UIImage *)image forState:(UIControlState)state134 {135[super setImage:image forState:state];136[self resetHitTestCache];137 }138 139 - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state140 {141[super setBackgroundImage:image forState:state];142[self resetHitTestCache];143 }144 145 - (void)resetHitTestCache146 {147self.previousTouchPoint = CGPointMake(CGFLOAT_MIN, CGFLOAT_MIN);148self.previousTouchHitTestResponse = NO;149 }150 151 @end

View Code

使用:

使用IB,添加一个UIButton,把关联类选择为OBShapedButton,把Button的Type修改为Custom,添加一个异形的Image,然后编译运行即可看到效果。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。