代码之家  ›  专栏  ›  技术社区  ›  floatingmuseum

如何使用Android SpannableString和MaskFilterSpan按预期模糊TextView中的一些文本?

  •  1
  • floatingmuseum  · 技术社区  · 7 年前

    我所期望的是这样的。 enter image description here 这是一个电影评论,当一些文字可能是剧透故事时,它会被这些标签[spoiler][spoiler]包裹起来。 所以我写了一个方法,找出每个扰流板文字的开始索引和结束索引,然后使用MaskFilterSpan对其进行模糊。

    但结果并不理想。

    enter image description here

    enter image description here enter image description here

    我的代码:

    private void testBlurText() {
        String text = "Alec Baldwin nailed his job; \n" +
                "The animators nailed their job (seriously, the art style and changes were amazing);\n" +
                "The ideas guy nailed his job ([spoiler]It's all the imagination of the kid[/spoiler]);\n" +
                "The writers just let the story down :( ([spoiler]Although at the beginning it's clear that the whole shebang is the older kid's imagination, the writers probably realised that the script was too short and so the end got changed to something that makes no sense. Why would Tim receive the kid for a second time? - unless it was all a dream...[/spoiler] ).\n" +
                "\n" +
                "All in all, a good movie, amazing acting and animating, partly let down by a badly written ending to the story. 8/10.";
        SpannableString spanText = new SpannableString(text);
        List<Pair<Integer, Integer>> spoilersContainer = new ArrayList<>();
        getSpoilerIndex(text, 0, spoilersContainer);
        for (Pair<Integer, Integer> pair : spoilersContainer) {
            spanText.setSpan(new MaskFilterSpan(new BlurMaskFilter(20, BlurMaskFilter.Blur.NORMAL)), pair.first, pair.second, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            Logger.d("SpoilerIndex:" + pair.toString());
        }
        tvTestBlurText.setText(spanText);
    }
    
    private void getSpoilerIndex(String rawComment, int beginIndex, List<Pair<Integer, Integer>> spoilersContainer) {
        int startIndex = rawComment.indexOf("[spoiler]", beginIndex);
        int endIndex = rawComment.indexOf("[/spoiler]", beginIndex);
        if (startIndex != -1 && endIndex != -1) {
            spoilersContainer.add(new Pair<>(startIndex, endIndex + "[/spoiler]".length()));
            getSpoilerIndex(rawComment, endIndex + "[/spoiler]".length(), spoilersContainer);
        }
    }
    

    有什么错吗,或者只是MaskFilterSpan的一个bug?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Bhuvanesh BS    7 年前

    如果设置 android:hardwareAccelerated="false" 关于您在中的活动 .

    硬件加速不支持BlurMaskFilter。

    http://developer.android.com/guide/topics/graphics/hardware-accel.html