Android 视图裁剪 [英] Android View Clipping

查看:29
本文介绍了Android 视图裁剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

android (Honeycomb) 中有没有什么方法可以定义一个 ViewGroup 的剪辑区域?例如,我有一个带有圆角图像背景的 ListView.当我滚动列表时,孩子们伸出背景的角落 - 我希望他们夹在圆角内.

Is there any way to define the clip region of a ViewGroup in android (Honeycomb)? For example, I have a ListView with an image background that has rounded corners. As I scroll through the list, the children stick out past the corners of the background - I would prefer them to clip within the rounded corners.

左图是它目前在做什么,右图是我想要的.

The left image is what it is currently doing, and the right is what I'd like.

我在看ClipDrawable,但好像只能用于进度条?

I was looking at ClipDrawable, but it seems that this may only be used for progress bars?

此外,我正在尝试在小部件中执行此操作.所以我不能使用自定义视图并覆盖 onDraw 进行遮罩.

Also, I'm trying to do this in a widget. So I cannot use a custom view and override onDraw for masking.

谢谢!

推荐答案

尝试子类化 ViewGroup 并按如下方式覆盖 OnDraw 方法,替换 RADIUS_IN_PIXELS 的值:

Try subclassing ViewGroup and overriding the OnDraw method as follows, substituting in values for RADIUS_IN_PIXELS:

@Override
protected void onDraw(Canvas canvas) {
    Path clipPath = new Path();
    clipPath.addRoundRect(new RectF(canvas.getClipBounds()), RADIUS_IN_PIXELS, RADIUS_IN_PIXELS, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
}

...并创建一个像这样的自定义可绘制对象,称为rounded",替换为 YOUR_BACKGROUND_COLOR 和 RADIUS_IN_DP,确保将 DP 中矩形的四舍五入与 PX 中之前的剪切半径匹配:

...and also create a custom drawable like this called something like 'rounded', substituting in YOUR_BACKGROUND_COLOR and RADIUS_IN_DP, making sure to match the rounding of the rectangle in DP to your previous clipping radius in PX:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="RADIUS_IN_DP" />
    <solid android:color="YOUR_BACKGROUND_COLOR"/>
</shape>

然后您可以在布局中使用该子类,添加行

Then you can use that subclass in your layout, adding the lines

android:background="@drawable/rounded"
android:clipChildren="true"

所有子项都将裁剪到您在 OnDraw() 覆盖中指定的边界,并且将根据您的圆形"可绘制对象添加背景.

All children will clip to the bounds you specify in the OnDraw() override, and a background will be added based on your 'rounded' drawable.

这篇关于Android 视图裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆