• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 选择时更改 UIBezierPath 颜色

[复制链接]
菜鸟教程小白 发表于 2022-12-13 04:37:29 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我在 LayoutView 中绘制了 3 个正方形

- (void)drawRectCGRect)rect

    self.room1 = [UIBezierPath bezierPathWithRect:CGRectMake(81, 10, 60, 60)];
    [self.normalColor setFill];
    [self.room1 fill];
    [[UIColor blackColor]setStroke];
    self.room1.lineWidth = 1;
    [self.room1 stroke];

然后我找到正确的 UIBezierPath

- (void)touchesBeganNSSet *)touches withEventUIEvent *)event
{
    NSLog(@"touch here");

    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    if ([self.room1 containsPoint:touchPoint])
    {
        // do stuff
        NSLog(@"room1 %@" , self.room1);

        [[UIColor redColor] setFill];
        [self.room1 fill];
        [self setNeedsDisplay];
    } 
}

这是工作我触摸房间 1 和日志打印“room1”

但是如何更改 room1 的颜色呢?

此时我得到一个错误

:CGContextSetFillColorWithColor:无效上下文 0x0。这是一个严重的错误。 ...

感谢您的帮助。



Best Answer-推荐答案


实现此目的的一种方法是在 touchesBegan 方法中跟踪选定状态,并将所有 fill 和 setFill 语句保留在 drawRect 中。在下面的示例中,我在方 block 内每次触摸时切换选定状态,方 block 颜色在蓝色和红色之间交替。

@interface RDView ()
@property (strong,nonatomic) UIBezierPath *room1;
@property (strong,nonatomic) UIColor *normalColor;
@property (strong,nonatomic) UIColor *selectedColor;
@property (nonatomic) BOOL isSelected;
@end

@implementation RDView

-(id)initWithCoderNSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.normalColor = [UIColor blueColor];
        self.selectedColor = [UIColor redColor];
        self.isSelected = NO;
    }
    return self;
}

- (void)drawRectCGRect)rect {

    self.room1 = [UIBezierPath bezierPathWithRect:CGRectMake(81, 10, 60, 60)];
    UIColor *colorToUse = (self.isSelected)? self.selectedColor : self.normalColor;
    [colorToUse setFill];
    [self.room1 fill];
    [[UIColor blackColor]setStroke];
    self.room1.lineWidth = 1;
    [self.room1 stroke];
}


- (void)touchesBeganNSSet *)touches withEventUIEvent *)event {
    CGPoint touchPoint = [touches.anyObject locationInView:self];
    if ([self.room1 containsPoint:touchPoint]){
        self.isSelected = ! self.isSelected;
        [self setNeedsDisplay];
    }
}

关于ios - 选择时更改 UIBezierPath 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19353923/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap