View组件添加边框

最近做项目的时候,恰好遇到给TextureView添加边框(专业名词为描边),因此查了一下相关资料。

网上有三种解决方案:

1.设置一个9 patch 的,右边框,中间是空的PNG。

2.自定义一个View,用Canvas画个边框。

3.用Android提供的ShapeDrawable来定义一个边框。

个人比较建议采用第三种方式,原因是因为第三种只要写XML,速度快,占用资源小,代码编写量也少,便于维护。

使用方法如下:

1.定义一个background.xml文件。


<?xml version="1.0" encoding="UTF-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke 
    android:width="2dp" 
    android:color="#0000AA" />    
</shape> 

2.在View的src设置背景时使用就可以了。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"  
        android:layout_height="match_parent" 
        android:gravity="center"
        android:src="@drawable/background"
        android:padding="2dp">  
        <TextureView          
            android:layout_width="match_parent"                              
            android:layout_height="match_parent"/>
        <com.android.camera.ui.RotateLayout
            android:layout_width="wrap_content"
            android:layout_width="wrap_content">
            <TextView
                 android:layout_width="wrap_content"
                 android:layout_width="wrap_content"
                 android:textColor="#FFFFFF"
                 android:textSize="22sp"
                 android:background="#0000000"/>
       </com.android.camera.ui.RoateLayout>
</RelativeLayout>
需要注意的是我给TextureView的父容器RelativeLayout设置了Drawable,并设置了Padding。

当然Android提供了比较丰富的resource,对于XML定义Drawable可以参考官方文档的Shape Drwable一节。

http://developer.android.com/guide/topics/resources/drawable-resource.html

转载于:https://my.oschina.net/shaorongjie/blog/195398

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值