android 实现图片的边框

本文介绍了如何在Android应用中通过继承ImageView并重写onDraw方法来为图片添加边框效果,提供了两种实现方案:一种是在图片周围绘制灰色边框,另一种是在灰色背景上内嵌图片并内缩像素。

方案一:继承ImageView,在onDraw 重写画图函数,在图片边延画条灰色的线

方案二:在灰色背景下,内缩2个像索,再内嵌个图片。

package com.xmz.activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.ImageView; public class ImageViewBorder extends ImageView { private String namespace="http://xmz.com"; private int color; public ImageViewBorder(Context context, AttributeSet attrs) { super(context, attrs); color=Color.parseColor(attrs.getAttributeValue(namespace, "BorderColor")); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //画边框 暂时去除小边框 Rect rec=canvas.getClipBounds(); rec.bottom--; rec.right--; Paint paint=new Paint(); paint.setColor(color); paint.setStyle(Paint.Style.STROKE); canvas.drawRect(rec, paint); } }

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xmz="http://xmz.com" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="方案一:" /> <com.xmz.activity.ImageViewBorder android:layout_width="124px" android:layout_height="180px" android:background="@drawable/movie" xmz:BorderColor="GRAY" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="方案二:" /> <LinearLayout android:layout_width="124px" android:layout_height="180px" android:background="@drawable/image_bg" android:padding="2px"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/movie" /> </LinearLayout> </LinearLayout>

工程的资源下载:http://download.youkuaiyun.com/source/3386837

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值