本文介绍了在UIView子类中使用的CAShapeLayer不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了几个小时在我的UIView周围使用CAShapeLayer获得虚线边框,但我没有显示它。

ScaleOverlay.h

i tried a few hours to get a dotted border around my UIView with CAShapeLayer but i don't get it displayed.
ScaleOverlay.h

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ScaleOverlay : UIView <UIGestureRecognizerDelegate> {
    CAShapeLayer *shapeLayer_;
}
@end

ScaleOverlay.m

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    self.backgroundColor = [UIColor redColor];
    self.alpha = 0;
    //Round corners
    [[self layer] setCornerRadius:8.f];
    [[self layer] setMasksToBounds:YES];
    //Border
    shapeLayer_ = [[CAShapeLayer layer] retain];

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, frame);
    shapeLayer_.path = path;
    CGPathRelease(path);
    shapeLayer_.backgroundColor = [[UIColor clearColor] CGColor];
    shapeLayer_.frame = frame;
    shapeLayer_.position = self.center;

    [shapeLayer_ setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"];
    shapeLayer_.fillColor = [[UIColor blueColor] CGColor];
    shapeLayer_.strokeColor = [[UIColor blackColor] CGColor];
    shapeLayer_.lineWidth = 4.;
    shapeLayer_.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:8], nil];
    shapeLayer_.lineCap = kCALineCapRound;
}
return self;
}

我在Superview中绘制了一个红色矩形,但没有绘制边框。从源代码示例中复制了这个,希望它可以工作,但事实并非如此。

I got a red rect drawn in my Superview but not the border. Copied this from a source example in the hope it would work, but it doesn't.

推荐答案

您永远不会添加 shapeLayer 作为UIView图层的子图层,所以它永远不会显示在屏幕上。尝试添加

You never add shapeLayer as a sublayer of your UIView's layer, so it's never displayed onscreen. Try adding

[self.layer addSublayer:shapeLayer_];

-initWithFrame中设置CAShapeLayer之后:方法。

更好的是,您可以尝试通过覆盖以下类方法来使您的UIView的支持层成为CAShapeLayer:

Even better, you could try making your UIView's backing layer a CAShapeLayer by overriding the following class method:

+ (Class) layerClass 
{
    return [CAShapeLayer class];
}

然后你可以直接处理视图层,并消除额外的CAShapeLayer实例变量。

You could then deal with the view's layer directly, and eliminate the additional CAShapeLayer instance variable.

这篇关于在UIView子类中使用的CAShapeLayer不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 11:38