简体   繁体   English

如何在Android中创建带有圆角边框的自定义视图

[英]How to create custom view with rounded border in Android

Hi, 你好

I'm trying to understand how to make custom view (with green background) on Android like represented on attached image. 我正在尝试了解如何在Android上制作自定义视图(带有绿色背景),如附加图像所示。 Please suggest, should I use Path for this or something else? 请提出建议,我应该使用Path还是其他?

附加图片

A good starting point would be http://tips.androidhive.info/2013/09/android-layout-rounded-corner-border/ . 一个不错的起点是http://tips.androidhive.info/2013/09/android-layout-rounded-corner-border/ Then you can play with the attribute values to get the desired background. 然后,您可以使用属性值来获取所需的背景。 Hope this helps. 希望这可以帮助。

You have two good options for accomplishing this. 您可以通过两个不错的选择来完成此任务。

Bitmap 位图

Create the desired image in Photoshop, Gimp or something similar. 在Photoshop,Gimp或类似工具中创建所需的图像。 Export it as a png file then import it as a bitmap resource into your Android application. 将其导出为png文件,然后将其作为位图资源导入到Android应用程序中。

This is by far the simpler and faster of the two methods, but here are two significant problems. 到目前为止,这是这两种方法中更简单,更快的方法,但是这里有两个重要的问题。 First, you should supply bitmaps for each screen density bucket . 首先,您应该为每个屏幕密度存储桶提供位图 Second, each bitmap resource you add increases the install size of your app. 其次,添加的每个位图资源都会增加应用程序的安装大小。 This can get out of hand quickly. 这会很快失控。

Path 路径

As you mentioned in your question, you can draw the desired shape directly onto a canvas using a Path . 正如您在问题中提到的那样,您可以使用Path将所需的形状直接绘制到画布上。 More specifically, you'll use the cubicTo() method to create bezier curves. 更具体地说,您将使用cubicTo()方法创建cubicTo()曲线。

I recommend using your image editor's "path" tool to learn how the control points affect the curve. 我建议使用图像编辑器的“路径”工具来了解控制点如何影响曲线。 Once you've drawn the shape in the image editor, write down the coordinates for every point on your path as well as the corresponding control points. 在图像编辑器中绘制形状后,记下路径上每个点以及相应控制点的坐标。 Then do a little math to convert the points to ratios of the image's overall width and height. 然后做一些数学运算,将点转换为图像整体宽度和高度的比率。

You can implement the shape in your app as a View or as a Drawable . 您可以在应用中将形状实现为ViewDrawable In either case, you'll be drawing to a Canvas . 无论哪种情况,您都将绘制到Canvas The important step will be to set up the path by multiplying the ratios with the size of your drawing area. 重要的步骤是通过将比例乘以绘图区域的大小来设置路径。 After you draw the fancy edge, be sure to draw the straight edges via lineTo() and to close the shape with close() . 绘制花式边缘后,请确保通过lineTo()绘制直线边缘,并使用close()关闭形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM