4

我有一个 UITextView,带有可滚动的文本。我正在尝试对其应用渐变层,因此可见文本的底部总是略微淡出。

这是我的代码:

CAGradientLayer *maskLayer = [CAGradientLayer layer];

maskLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor yellowColor] CGColor], nil];
maskLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
                       [NSNumber numberWithFloat:0.2],
                       [NSNumber numberWithFloat:0.8],
                       [NSNumber numberWithFloat:1.0], nil];
maskLayer.bounds = clueTextView.bounds;
myUITextView.layer.mask = maskLayer;

现在,这导致 UITextViewLayer 完全透明 - 我看到 UITextViewLayer 作为子视图的 UIView 的背景颜色。我看不到其中包含的任何文本,尽管我可以选择并复制文本以粘贴到笔记程序中。

有什么我想念的想法吗?

4

1 回答 1

12

你有几个问题。

渐变层的colors属性需要与其locations属性具有相同的计数。您提供 4 个位置,但仅提供 2 种颜色。

您正在设置渐变层的边界,clueTextView但您将其设置为myUITextView.

您正在设置bounds渐变层的 ,但不是它的position。默认position值为 0,0,表示渐变层的中心位于 的左上角myUITextViewframe将渐变层的设置bounds为文本视图更简单。

如果你解决了所有这些问题,你可能会得到你想要的效果。

- (void)initTextViewMask {
    CAGradientLayer *maskLayer = [CAGradientLayer layer];
    maskLayer.colors = @[
        (id)[UIColor whiteColor].CGColor,
        (id)[UIColor whiteColor].CGColor,
        (id)[UIColor clearColor].CGColor];
    maskLayer.locations = @[ @0.0f, @0.8f, @1.0f ];
    maskLayer.frame = textView_.bounds;
    textView_.layer.mask = maskLayer;
}

但是,您可能会发现新的问题。

如果用户可以滚动文本视图,你会发现渐变随着文本视图移动,这可能不是你想要的。解决此问题的最简单方法是将文本视图嵌入到容器中UIView,并在容器视图上设置掩码。

如果文本视图可以改变大小(可能是由于设备旋转),遮罩不会自动改变大小。您需要更新掩码的frame, inlayoutSubviewsviewDidLayoutSubviews.

于 2012-10-11T18:39:49.230 回答