我有一个带有3个ImageView的LinearLayout。每当用户点击ImageView时,我想在ImageView上绘制一个周围的矩形。我知道如何在ImageView上绘制内容,但我想直接在LinearLayout上绘制。
我该怎么做? 我已经编写了以下代码:
setContentView(R.id.anaekran2);
LinearLayout linLayout = (LinearLayout) findViewById(R.id.layout01);
有类似linLayout.getCanvas()
的内容吗?
我找不到类似的功能,但我发现了
linLayout.getDrawingCache()
。所以,
Bitmap b = linLayout.getDrawingCache();
Canvas c = new Canvas(b); // this line gives an error, why?
答案 0 :(得分:1)
您应该创建自定义线性布局。覆盖onDraw线性布局方法可以解决您的问题。这是自定义线性布局代码。
public class CustomLinearLayout extends LinearLayout {
private Paint mPaint;
private int mClickedChild = -1;
public CustomLinearLayout(Context context) {
super(context);
setWillNotDraw(false);
createPaint();
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
createPaint();
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setWillNotDraw(false);
createPaint();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
initializeChildrenClickEvent();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(mClickedChild != -1){
View child = getChildAt(mClickedChild);
canvas.drawRect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom(), mPaint);
}
}
private void initializeChildrenClickEvent(){
final int childCount = getChildCount();
OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View view) {
for(int i = 0; i < childCount; i++){
if(getChildAt(i).equals(view)){
mClickedChild = i;
break;
}
}
invalidate();
}
};
for(int i = 0; i < childCount; i++){
getChildAt(i).setOnClickListener(clickListener);
}
}
private void createPaint(){
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(5f);
}
}
以下是xml中自定义布局的用法。
<CustomLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image_view_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/image_view_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/image_view_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="@drawable/ic_launcher" />
</CustomLinearLayout>